Convert to more of a mixture of "DBIC" and "DBIx::Class" as per suggestion from Castaway
[catagits/Catalyst-Manual.git] / lib / Catalyst / Manual / Tutorial / Authentication.pod
CommitLineData
d442cc9f 1=head1 NAME
2
4b4d3884 3Catalyst::Manual::Tutorial::Authentication - Catalyst Tutorial - Chapter 5: Authentication
d442cc9f 4
5
6=head1 OVERVIEW
7
4b4d3884 8This is B<Chapter 5 of 10> for the Catalyst tutorial.
d442cc9f 9
10L<Tutorial Overview|Catalyst::Manual::Tutorial>
11
12=over 4
13
14=item 1
15
16L<Introduction|Catalyst::Manual::Tutorial::Intro>
17
18=item 2
19
20L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics>
21
22=item 3
23
3533daff 24L<More Catalyst Basics|Catalyst::Manual::Tutorial::MoreCatalystBasics>
d442cc9f 25
26=item 4
27
3533daff 28L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD>
d442cc9f 29
30=item 5
31
3533daff 32B<Authentication>
d442cc9f 33
34=item 6
35
3533daff 36L<Authorization|Catalyst::Manual::Tutorial::Authorization>
d442cc9f 37
38=item 7
39
3533daff 40L<Debugging|Catalyst::Manual::Tutorial::Debugging>
d442cc9f 41
42=item 8
43
3533daff 44L<Testing|Catalyst::Manual::Tutorial::Testing>
d442cc9f 45
46=item 9
47
3533daff 48L<Advanced CRUD|Catalyst::Manual::Tutorial::AdvancedCRUD>
d442cc9f 49
3533daff 50=item 10
d442cc9f 51
3533daff 52L<Appendices|Catalyst::Manual::Tutorial::Appendices>
d442cc9f 53
3533daff 54=back
2d0526d1 55
2d0526d1 56
d442cc9f 57=head1 DESCRIPTION
58
905a3a26 59Now that we finally have a simple yet functional application, we can
60focus on providing authentication (with authorization coming next in
4b4d3884 61Chapter 6).
d442cc9f 62
4b4d3884 63This chapter of the tutorial is divided into two main sections: 1) basic,
d442cc9f 64cleartext authentication and 2) hash-based authentication.
65
66You can checkout the source code for this example from the catalyst
67subversion repository as per the instructions in
1390ef0e 68L<Catalyst::Manual::Tutorial::Intro|Catalyst::Manual::Tutorial::Intro>.
d442cc9f 69
fbbb9084 70
d442cc9f 71=head1 BASIC AUTHENTICATION
72
73This section explores how to add authentication logic to a Catalyst
74application.
75
76
77=head2 Add Users and Roles to the Database
78
79First, we add both user and role information to the database (we will
80add the role information here although it will not be used until the
4b4d3884 81authorization section, Chapter 6). Create a new SQL script file by opening
d442cc9f 82C<myapp02.sql> in your editor and insert:
83
84 --
85 -- Add users and roles tables, along with a many-to-many join table
86 --
87 CREATE TABLE users (
88 id INTEGER PRIMARY KEY,
89 username TEXT,
90 password TEXT,
91 email_address TEXT,
92 first_name TEXT,
93 last_name TEXT,
94 active INTEGER
95 );
96 CREATE TABLE roles (
97 id INTEGER PRIMARY KEY,
98 role TEXT
99 );
100 CREATE TABLE user_roles (
101 user_id INTEGER,
102 role_id INTEGER,
103 PRIMARY KEY (user_id, role_id)
104 );
105 --
106 -- Load up some initial test data
107 --
108 INSERT INTO users VALUES (1, 'test01', 'mypass', 't01@na.com', 'Joe', 'Blow', 1);
109 INSERT INTO users VALUES (2, 'test02', 'mypass', 't02@na.com', 'Jane', 'Doe', 1);
110 INSERT INTO users VALUES (3, 'test03', 'mypass', 't03@na.com', 'No', 'Go', 0);
111 INSERT INTO roles VALUES (1, 'user');
112 INSERT INTO roles VALUES (2, 'admin');
113 INSERT INTO user_roles VALUES (1, 1);
114 INSERT INTO user_roles VALUES (1, 2);
115 INSERT INTO user_roles VALUES (2, 1);
116 INSERT INTO user_roles VALUES (3, 1);
117
118Then load this into the C<myapp.db> database with the following command:
119
120 $ sqlite3 myapp.db < myapp02.sql
121
122
123=head2 Add User and Role Information to DBIC Schema
124
3533daff 125Although we could manually edit the DBIC schema information to include
126the new tables added in the previous step, let's use the C<create=static>
127option on the DBIC model helper to do most of the work for us:
d442cc9f 128
acbd7bdd 129 $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \
130 create=static components=TimeStamp dbi:SQLite:myapp.db
1390ef0e 131 exists "/root/dev/MyApp/script/../lib/MyApp/Model"
132 exists "/root/dev/MyApp/script/../t"
133 Dumping manual schema for MyApp::Schema to directory /root/dev/MyApp/script/../lib ...
134 Schema dump completed.
135 exists "/root/dev/MyApp/script/../lib/MyApp/Model/DB.pm"
136 $
acbd7bdd 137 $ ls lib/MyApp/Schema/Result
3533daff 138 Authors.pm BookAuthors.pm Books.pm Roles.pm UserRoles.pm Users.pm
d442cc9f 139
905a3a26 140Notice how the helper has added three new table-specific result source
acbd7bdd 141files to the C<lib/MyApp/Schema/Result> directory. And, more
905a3a26 142importantly, even if there were changes to the existing result source
143files, those changes would have only been written above the C<# DO NOT
191dee29 144MODIFY THIS OR ANYTHING ABOVE!> comment and your hand-edited
3533daff 145enhancements would have been preserved.
d442cc9f 146
191dee29 147Speaking of "hand-edit ted enhancements," we should now add
905a3a26 148relationship information to the three new result source files. Edit
149each of these files and add the following information between the C<#
3533daff 150DO NOT MODIFY THIS OR ANYTHING ABOVE!> comment and the closing C<1;>:
d442cc9f 151
acbd7bdd 152C<lib/MyApp/Schema/Result/Users.pm>:
d442cc9f 153
d442cc9f 154 #
155 # Set relationships:
156 #
efdaddec 157
d442cc9f 158 # has_many():
159 # args:
160 # 1) Name of relationship, DBIC will create accessor with this name
161 # 2) Name of the model class referenced by this relationship
1435672d 162 # 3) Column name in *foreign* table (aka, foreign key in peer table)
acbd7bdd 163 __PACKAGE__->has_many(map_user_role => 'MyApp::Schema::Result::UserRoles', 'user_id');
efdaddec 164
3533daff 165 # many_to_many():
166 # args:
167 # 1) Name of relationship, DBIC will create accessor with this name
905a3a26 168 # 2) Name of has_many() relationship this many_to_many() is shortcut for
169 # 3) Name of belongs_to() relationship in model class of has_many() above
3533daff 170 # You must already have the has_many() defined to use a many_to_many().
171 __PACKAGE__->many_to_many(roles => 'map_user_role', 'role');
d442cc9f 172
173
acbd7bdd 174C<lib/MyApp/Schema/Result/Roles.pm>:
d442cc9f 175
d442cc9f 176 #
177 # Set relationships:
178 #
efdaddec 179
d442cc9f 180 # has_many():
181 # args:
182 # 1) Name of relationship, DBIC will create accessor with this name
183 # 2) Name of the model class referenced by this relationship
1435672d 184 # 3) Column name in *foreign* table (aka, foreign key in peer table)
acbd7bdd 185 __PACKAGE__->has_many(map_user_role => 'MyApp::Schema::Result::UserRoles', 'role_id');
d442cc9f 186
187
acbd7bdd 188C<lib/MyApp/Schema/Result/UserRoles.pm>:
d442cc9f 189
d442cc9f 190 #
191 # Set relationships:
192 #
efdaddec 193
d442cc9f 194 # belongs_to():
195 # args:
196 # 1) Name of relationship, DBIC will create accessor with this name
197 # 2) Name of the model class referenced by this relationship
198 # 3) Column name in *this* table
acbd7bdd 199 __PACKAGE__->belongs_to(user => 'MyApp::Schema::Result::Users', 'user_id');
efdaddec 200
d442cc9f 201 # belongs_to():
202 # args:
203 # 1) Name of relationship, DBIC will create accessor with this name
204 # 2) Name of the model class referenced by this relationship
205 # 3) Column name in *this* table
acbd7bdd 206 __PACKAGE__->belongs_to(role => 'MyApp::Schema::Result::Roles', 'role_id');
d442cc9f 207
3533daff 208
905a3a26 209The code for these three sets of updates is obviously very similar to
210the edits we made to the C<Books>, C<Authors>, and C<BookAuthors>
4b4d3884 211classes created in Chapter 3.
3533daff 212
636ba9f7 213Note that we do not need to make any change to the
214C<lib/MyApp/Schema.pm> schema file. It simply tells DBIC to load all
215of the Result Class and ResultSet Class files it finds in below the
216C<lib/MyApp/Schema> directory, so it will automatically pick up our
acbd7bdd 217new table information.
d442cc9f 218
219
220=head2 Sanity-Check Reload of Development Server
221
905a3a26 222We aren't ready to try out the authentication just yet; we only want
223to do a quick check to be sure our model loads correctly. Press
224C<Ctrl-C> to kill the previous server instance (if it's still running)
3533daff 225and restart it:
d442cc9f 226
227 $ script/myapp_server.pl
228
229Look for the three new model objects in the startup debug output:
230
231 ...
232 .-------------------------------------------------------------------+----------.
233 | Class | Type |
234 +-------------------------------------------------------------------+----------+
235 | MyApp::Controller::Books | instance |
236 | MyApp::Controller::Root | instance |
d0496197 237 | MyApp::Model::DB | instance |
238 | MyApp::Model::DB::Author | class |
239 | MyApp::Model::DB::Books | class |
240 | MyApp::Model::DB::BookAuthors | class |
241 | MyApp::Model::DB::Roles | class |
242 | MyApp::Model::DB::Users | class |
243 | MyApp::Model::DB::UserRoles | class |
d442cc9f 244 | MyApp::View::TT | instance |
245 '-------------------------------------------------------------------+----------'
246 ...
247
acbd7bdd 248Again, notice that your "Result Class" classes have been "re-loaded"
3533daff 249by Catalyst under C<MyApp::Model>.
d442cc9f 250
251
252=head2 Include Authentication and Session Plugins
253
905a3a26 254Edit C<lib/MyApp.pm> and update it as follows (everything below
3533daff 255C<StackTrace> is new):
d442cc9f 256
acbd7bdd 257 # Load plugins
258 use Catalyst qw/-Debug
259 ConfigLoader
260 Static::Simple
efdaddec 261
acbd7bdd 262 StackTrace
efdaddec 263
acbd7bdd 264 Authentication
efdaddec 265
acbd7bdd 266 Session
267 Session::Store::FastMmap
268 Session::State::Cookie
269 /;
d442cc9f 270
636ba9f7 271B<Note:> As discussed in MoreCatalystBasics, different versions of
272C<Catalyst::Devel> have used a variety of methods to load the plugins.
533fee73 273You can put the plugins in the C<use Catalyst> statement if you prefer.
94d8da41 274
905a3a26 275The C<Authentication> plugin supports Authentication while the
276C<Session> plugins are required to maintain state across multiple HTTP
277requests.
6d0971ad 278
905a3a26 279Note that the only required Authentication class is the main one. This
280is a change that occurred in version 0.09999_01 of the
281C<Authentication> plugin. You B<do not need> to specify a particular
282Authentication::Store or Authentication::Credential plugin. Instead,
283indicate the Store and Credential you want to use in your application
6d0971ad 284configuration (see below).
285
905a3a26 286Note that there are several options for
287L<Session::Store|Catalyst::Plugin::Session::Store>
288(L<Session::Store::FastMmap|Catalyst::Plugin::Session::Store::FastMmap>
289is generally a good choice if you are on Unix; try
290L<Session::Store::File|Catalyst::Plugin::Session::Store::File> if you
291are on Win32) -- consult
292L<Session::Store|Catalyst::Plugin::Session::Store> and its subclasses
3533daff 293for additional information and options (for example to use a database-
294backed session store).
d442cc9f 295
296
297=head2 Configure Authentication
298
efdaddec 299There are a variety of way to provide configuration information to
300L<Catalyst::Plugin::Authentication|Catalyst::Plugin::Authentication>.
301Here we will use
302L<Catalyst::Authentication::Realm::SimpleDB|Catalyst::Authentication::Realm::SimpleDB>
303because it automatically sets a reasonable set of defaults for us. Open
304C<lib/MyApp.pm> and place the following text above the call to
305C<__PACKAGE__-E<gt>setup();>:
306
307 # Configure SimpleDB Authentication
308 __PACKAGE__->config->{'Plugin::Authentication'} = {
309 default => {
310 class => 'SimpleDB',
311 user_model => 'DB::Users',
312 password_type => 'clear',
313 },
314 };
315
316We could have placed this configuration in C<myapp.conf>, but placing
317it in C<lib/MyApp.pm> is probably a better place since it's not likely
318something that users of your application will want to change during
c3cf3bc3 319deployment (or you could use a mixture: leave C<class> and
320C<user_model> defined in C<lib/MyApp.pm> as we show above, but place
321C<password_type> in C<myapp.conf> to allow the type of password to be
322easily modified during deployment). We will stick with putting
323all of the authentication-related configuration in C<lib/MyApp.pm>
324for the tutorial, but if you wish to use C<myapp.conf>, just convert
325to the following code:
326
327 <Plugin::Authentication>
328 use_session 1
329 <default>
330 password_type self_check
331 user_model DB::Users
332 class SimpleDB
333 </default>
334 </Plugin::Authentication>
335
336B<TIP:> Here is a short script that will dump the contents of
337C<MyApp->config> to L<Config::General|Config::General> format in
338C<myapp.conf>:
339
340 $ perl -Ilib -e 'use MyApp; use Config::General;
341 Config::General->new->save_file("myapp.conf", MyApp->config);'
d442cc9f 342
1390ef0e 343
d442cc9f 344=head2 Add Login and Logout Controllers
345
346Use the Catalyst create script to create two stub controller files:
347
348 $ script/myapp_create.pl controller Login
349 $ script/myapp_create.pl controller Logout
350
636ba9f7 351You could easily use a single controller here. For example, you could
352have a C<User> controller with both C<login> and C<logout> actions.
353Remember, Catalyst is designed to be very flexible, and leaves such
fbbb9084 354matters up to you, the designer and programmer.
d442cc9f 355
636ba9f7 356Then open C<lib/MyApp/Controller/Login.pm>, locate the
357C<sub index :Path :Args(0)> method (or C<sub index : Private> if you
358are using an older version of Catalyst) that was automatically
359inserted by the helpers when we created the Login controller above,
fbbb9084 360and update the definition of C<sub index> to match:
d442cc9f 361
362 =head2 index
efdaddec 363
d442cc9f 364 Login logic
efdaddec 365
d442cc9f 366 =cut
efdaddec 367
ae492862 368 sub index :Path :Args(0) {
d442cc9f 369 my ($self, $c) = @_;
efdaddec 370
d442cc9f 371 # Get the username and password from form
372 my $username = $c->request->params->{username} || "";
373 my $password = $c->request->params->{password} || "";
efdaddec 374
d442cc9f 375 # If the username and password values were found in form
376 if ($username && $password) {
377 # Attempt to log the user in
905a3a26 378 if ($c->authenticate({ username => $username,
5fefca35 379 password => $password } )) {
d442cc9f 380 # If successful, then let them use the application
0416017e 381 $c->response->redirect($c->uri_for(
382 $c->controller('Books')->action_for('list')));
d442cc9f 383 return;
384 } else {
385 # Set an error message
386 $c->stash->{error_msg} = "Bad username or password.";
387 }
388 }
efdaddec 389
d442cc9f 390 # If either of above don't work out, send to the login page
391 $c->stash->{template} = 'login.tt2';
392 }
393
394This controller fetches the C<username> and C<password> values from the
905a3a26 395login form and attempts to authenticate the user. If successful, it
396redirects the user to the book list page. If the login fails, the user
397will stay at the login page and receive an error message. If the
398C<username> and C<password> values are not present in the form, the
f632e28b 399user will be taken to the empty login form.
d442cc9f 400
636ba9f7 401Note that we could have used something like "C<sub default :Path>",
402however, it is generally recommended (partly for historical reasons,
403and partly for code clarity) only to use C<default> in
404C<MyApp::Controller::Root>, and then mainly to generate the 404 not
85d49fb6 405found page for the application.
ae492862 406
fbbb9084 407Instead, we are using "C<sub somename :Path :Args(0) {...}>" here to
905a3a26 408specifically match the URL C</login>. C<Path> actions (aka, "literal
409actions") create URI matches relative to the namespace of the
410controller where they are defined. Although C<Path> supports
411arguments that allow relative and absolute paths to be defined, here
412we use an empty C<Path> definition to match on just the name of the
413controller itself. The method name, C<index>, is arbitrary. We make
ae492862 414the match even more specific with the C<:Args(0)> action modifier --
905a3a26 415this forces the match on I<only> C</login>, not
d442cc9f 416C</login/somethingelse>.
417
905a3a26 418Next, update the corresponding method in
3533daff 419C<lib/MyApp/Controller/Logout.pm> to match:
d442cc9f 420
421 =head2 index
efdaddec 422
d442cc9f 423 Logout logic
efdaddec 424
d442cc9f 425 =cut
efdaddec 426
ae492862 427 sub index :Path :Args(0) {
d442cc9f 428 my ($self, $c) = @_;
efdaddec 429
d442cc9f 430 # Clear the user's state
431 $c->logout;
efdaddec 432
d442cc9f 433 # Send the user to the starting point
434 $c->response->redirect($c->uri_for('/'));
435 }
436
905a3a26 437As with the login controller, be sure to delete the
14e5ed66 438C<$c-E<gt>response-E<gt>body('Matched MyApp::Controller::Logout in Logout.');>
d442cc9f 439line of the C<sub index>.
440
441
442=head2 Add a Login Form TT Template Page
443
444Create a login form by opening C<root/src/login.tt2> and inserting:
445
446 [% META title = 'Login' %]
efdaddec 447
d442cc9f 448 <!-- Login form -->
8a7c5151 449 <form method="post" action="[% c.uri_for('/login') %]">
d442cc9f 450 <table>
451 <tr>
452 <td>Username:</td>
453 <td><input type="text" name="username" size="40" /></td>
454 </tr>
455 <tr>
456 <td>Password:</td>
457 <td><input type="password" name="password" size="40" /></td>
458 </tr>
459 <tr>
460 <td colspan="2"><input type="submit" name="submit" value="Submit" /></td>
461 </tr>
462 </table>
463 </form>
464
465
466=head2 Add Valid User Check
467
468We need something that provides enforcement for the authentication
469mechanism -- a I<global> mechanism that prevents users who have not
470passed authentication from reaching any pages except the login page.
471This is generally done via an C<auto> action/method (prior to Catalyst
472v5.66, this sort of thing would go in C<MyApp.pm>, but starting in
473v5.66, the preferred location is C<lib/MyApp/Controller/Root.pm>).
474
475Edit the existing C<lib/MyApp/Controller/Root.pm> class file and insert
476the following method:
477
478 =head2 auto
efdaddec 479
d442cc9f 480 Check if there is a user and, if not, forward to login page
efdaddec 481
d442cc9f 482 =cut
efdaddec 483
d442cc9f 484 # Note that 'auto' runs after 'begin' but before your actions and that
905a3a26 485 # 'auto's "chain" (all from application path to most specific class are run)
d442cc9f 486 # See the 'Actions' section of 'Catalyst::Manual::Intro' for more info.
487 sub auto : Private {
488 my ($self, $c) = @_;
efdaddec 489
d442cc9f 490 # Allow unauthenticated users to reach the login page. This
191dee29 491 # allows unauthenticated users to reach any action in the Login
d442cc9f 492 # controller. To lock it down to a single action, we could use:
493 # if ($c->action eq $c->controller('Login')->action_for('index'))
905a3a26 494 # to only allow unauthenticated access to the 'index' action we
d442cc9f 495 # added above.
496 if ($c->controller eq $c->controller('Login')) {
497 return 1;
498 }
efdaddec 499
d442cc9f 500 # If a user doesn't exist, force login
501 if (!$c->user_exists) {
502 # Dump a log message to the development server debug output
503 $c->log->debug('***Root::auto User not found, forwarding to /login');
504 # Redirect the user to the login page
505 $c->response->redirect($c->uri_for('/login'));
506 # Return 0 to cancel 'post-auto' processing and prevent use of application
507 return 0;
508 }
efdaddec 509
d442cc9f 510 # User found, so return 1 to continue with processing after this 'auto'
511 return 1;
512 }
513
636ba9f7 514As discussed in
515L<Catalyst::Manual::Tutorial::MoreCatalystBasics/CREATE A CATALYST CONTROLLER>,
516every C<auto> method from the application/root controller down to the
517most specific controller will be called. By placing the
518authentication enforcement code inside the C<auto> method of
519C<lib/MyApp/Controller/Root.pm> (or C<lib/MyApp.pm>), it will be
520called for I<every> request that is received by the entire
0416017e 521application.
d442cc9f 522
523
524=head2 Displaying Content Only to Authenticated Users
525
526Let's say you want to provide some information on the login page that
527changes depending on whether the user has authenticated yet. To do
528this, open C<root/src/login.tt2> in your editor and add the following
529lines to the bottom of the file:
530
acbd7bdd 531 ...
d442cc9f 532 <p>
533 [%
905a3a26 534 # This code illustrates how certain parts of the TT
d442cc9f 535 # template will only be shown to users who have logged in
536 %]
8a7c5151 537 [% IF c.user_exists %]
538 Please Note: You are already logged in as '[% c.user.username %]'.
539 You can <a href="[% c.uri_for('/logout') %]">logout</a> here.
d442cc9f 540 [% ELSE %]
541 You need to log in to use this application.
542 [% END %]
543 [%#
544 Note that this whole block is a comment because the "#" appears
905a3a26 545 immediate after the "[%" (with no spaces in between). Although it
546 can be a handy way to temporarily "comment out" a whole block of
547 TT code, it's probably a little too subtle for use in "normal"
d442cc9f 548 comments.
549 %]
3533daff 550 </p>
d442cc9f 551
552Although most of the code is comments, the middle few lines provide a
553"you are already logged in" reminder if the user returns to the login
554page after they have already authenticated. For users who have not yet
555authenticated, a "You need to log in..." message is displayed (note the
556use of an IF-THEN-ELSE construct in TT).
557
558
559=head2 Try Out Authentication
560
561Press C<Ctrl-C> to kill the previous server instance (if it's still
562running) and restart it:
563
564 $ script/myapp_server.pl
565
636ba9f7 566B<IMPORTANT NOTE:> If you are having issues with authentication on
567Internet Explorer, be sure to check the system clocks on both your
568server and client machines. Internet Explorer is very picky about
acbd7bdd 569timestamps for cookies. You can quickly sync a Debian system by
570installing the "ntpdate" package:
571
572 sudo aptitude -y install ntpdate
573
574And then run the following command:
25ed8f40 575
acbd7bdd 576 sudo ntpdate-debian
d442cc9f 577
acbd7bdd 578Or, depending on your firewall configuration:
579
580 sudo ntpdate-debian -u
581
636ba9f7 582Note: NTP can be a little more finicky about firewalls because it uses
acbd7bdd 583UDP vs. the more common TCP that you see with most Internet protocols.
584Worse case, you might have to manually set the time on your development
585box instead of using NTP.
1390ef0e 586
636ba9f7 587Now trying going to L<http://localhost:3000/books/list> and you should
588be redirected to the login page, hitting Shift+Reload or Ctrl+Reload
589if necessary (the "You are already logged in" message should I<not>
590appear -- if it does, click the C<logout> button and try again). Note
591the C<***Root::auto User not found...> debug message in the
592development server output. Enter username C<test01> and password
1390ef0e 593C<mypass>, and you should be taken to the Book List page.
d442cc9f 594
595Open C<root/src/books/list.tt2> and add the following lines to the
3533daff 596bottom (below the closing </table> tag):
d442cc9f 597
598 <p>
8a7c5151 599 <a href="[% c.uri_for('/login') %]">Login</a>
0416017e 600 <a href="[% c.uri_for(c.controller.action_for('form_create')) %]">Create</a>
d442cc9f 601 </p>
602
905a3a26 603Reload your browser and you should now see a "Login" and "Create" links
604at the bottom of the page (as mentioned earlier, you can update template
605files without reloading the development server). Click the first link
606to return to the login page. This time you I<should> see the "You are
d442cc9f 607already logged in" message.
608
609Finally, click the C<You can logout here> link on the C</login> page.
610You should stay at the login page, but the message should change to "You
611need to log in to use this application."
612
613
614=head1 USING PASSWORD HASHES
615
efdaddec 616In this section we increase the security of our system by converting
617from cleartext passwords to SHA-1 password hashes that include a
618random "salt" value to make them extremely difficult to crack with
619dictionary and "rainbow table" attacks.
d442cc9f 620
621B<Note:> This section is optional. You can skip it and the rest of the
622tutorial will function normally.
623
fbbb9084 624Be aware that even with the techniques shown in this section, the browser
d442cc9f 625still transmits the passwords in cleartext to your application. We are
626just avoiding the I<storage> of cleartext passwords in the database by
efdaddec 627using a salted SHA-1 hash. If you are concerned about cleartext passwords
d442cc9f 628between the browser and your application, consider using SSL/TLS, made
efdaddec 629easy with the Catalyst plugin Catalyst::Plugin:RequireSSL.
d442cc9f 630
631
efdaddec 632=head2 Install DBIx::Class::EncodedColumn
d442cc9f 633
efdaddec 634L<DBIx::Class::EncodedColumn|DBIx::Class::EncodedColumn> provides features
635that can greatly simplify the maintenance of passwords. It's currently
636not available as a .deb package in the normal Debian repositories, so let's
637install it directly from CPAN:
d442cc9f 638
efdaddec 639 $ sudo cpan DBIx::Class::EncodedColumn
d0496197 640
d442cc9f 641
efdaddec 642=head2 Re-Run the DBIC::Schema Model Helper to Include DBIx::Class::EncodedColumn
d442cc9f 643
efdaddec 644Next, we can re-run the model helper to have it include
645L<DBIx::Class::EncodedColumn|DBIx::Class::EncodedColumn> in all of the
646Result Classes it generates for us. Simply use the same command we
647saw in Chapters 3 and 4, but add C<,EncodedColumn> to the C<components>
648argument:
d442cc9f 649
efdaddec 650 $ script/myapp_create.pl model DB DBIC::Schema MyApp::Schema \
651 create=static components=TimeStamp,EncodedColumn dbi:SQLite:myapp.db
d442cc9f 652
efdaddec 653If you then open one of the Result Classes, you will see that it
654includes EncodedColumn in the C<load_components> line. Take a look at
655C<lib/MyApp/Schema/Result/Users.pm> since that's the main class where we
656want to use hashed and salted passwords:
657
658 __PACKAGE__->load_components("InflateColumn::DateTime", "TimeStamp", "EncodedColumn", "Core");
659
660
661=head2 Modify the "password" Column to Use EncodedColumn
662
663Open the file C<lib/MyApp/Schema/Result/Users.pm> and enter the following
664text below the "# DO NOT MODIFY THIS OR ANYTHING ABOVE!" line but above
665the closing "1;":
666
667 # Have the 'password' column use a SHA-1 hash and 10-character salt
668 # with hex encoding; Generate the 'check_password" method
669 __PACKAGE__->add_columns(
670 'password' => {
671 data_type => "TEXT",
672 size => undef,
673 encode_column => 1,
674 encode_class => 'Digest',
675 encode_args => {salt_length => 10},
676 encode_check_method => 'check_password',
677 },
678 );
679
680This redefines the automatically generated definition for the password
681fields at the top of the Result Class file to now use EncodedColumn
682logic (C<encoded_column> is set to 1). C<encode_class> can be set to
683either C<Digest> to use
684L<DBIx::Class::EncodedColumn::Digest|DBIx::Class::EncodedColumn::Digest>,
685or C<Crypt::Eksblowfish::Bcrypt> for
686L<DBIx::Class::EncodedColumn::Crypt::Eksblowfish::Bcrypt|DBIx::Class::EncodedColumn::Crypt::Eksblowfish::Bcrypt>.
687C<encode_args> is then used to customize the type of Digest you
688selected. Here we only specified the size of the salt to use, but
689we could have also modified the hashing algorithm ('SHA-256' is
690the default) and the format to use ('base64' is the default, but
691'hex' and 'binary' are other options). To use these, you could
692change the C<encode_args> to something like:
693
694 encode_args => {algorithm => 'SHA-1',
695 format => 'hex',
696 salt_length => 10},
697
698
699=head2 Load Hashed Passwords in the Database
700
701Next, let's create a quick script to load some hashed and salted passwords
702into the C<password> column of our C<users> table. Open the file
703C<set_hashed_passwords.pl> in your editor and enter the following text:
704
705 #!/usr/bin/perl
706
707 use strict;
708 use warnings;
709
710 use MyApp::Schema;
711
712 my $schema = MyApp::Schema->connect('dbi:SQLite:myapp.db');
713
714 my @users = $schema->resultset('Users')->all;
715
716 foreach my $user (@users) {
717 $user->password('mypass');
718 $user->update;
719 }
720
721EncodedColumn lets us simple call C<$user->check_password($password)>
722to see if the user has supplied the correct password, or, as we show
723above, call C<$user->update($new_password)> to update the hashed
724password stored for this user.
725
726Then run the following command:
727
728 $ perl -Ilib set_hashed_passwords.pl
729
730We had to use the C<-Ilib> arguement to tell perl to look under the
731C<lib> directory for our C<MyApp::Schema> model.
732
733Then dump the users table to verify that it worked:
734
735 $ sqlite3 myapp.db "select * from users"
736 1|test01|38d3974fa9e9263099f7bc2574284b2f55473a9bM=fwpX2NR8|t01@na.com|Joe|Blow|1
737 2|test02|6ed8586587e53e0d7509b1cfed5df08feadc68cbMJlnPyPt0I|t02@na.com|Jane|Doe|1
738 3|test03|af929a151340c6aed4d54d7e2651795d1ad2e2f7UW8dHoGv9z|t03@na.com|No|Go|0
739
740As you can see, the passwords are much harder to steal from the
741database. Also note that this demonstrates how to use a DBIx::Class
742model outside of your web application -- a very useful feature in many
743situations.
744
745
746=head2 Enable Hashed and Salted Passwords
747
748Edit C<lib/MyApp.pm> and update it to match the following text (the only change
749is to the C<password_type> field):
750
751 # Configure SimpleDB Authentication
752 __PACKAGE__->config->{'Plugin::Authentication'} = {
753 default => {
754 class => 'SimpleDB',
755 user_model => 'DB::Users',
756 password_type => 'self_check',
757 },
758 };
759
760The use of C<self_check> will cause
761Catalyst::Plugin::Authentication::Store::DBIC to call the
762C<check_password> method we enabled on our C<password> columns.
d442cc9f 763
1390ef0e 764
d442cc9f 765=head2 Try Out the Hashed Passwords
766
767Press C<Ctrl-C> to kill the previous server instance (if it's still
768running) and restart it:
769
770 $ script/myapp_server.pl
771
772You should now be able to go to L<http://localhost:3000/books/list> and
fbbb9084 773login as before. When done, click the "logout" link on the login page
d442cc9f 774(or point your browser at L<http://localhost:3000/logout>).
775
d442cc9f 776
777=head1 USING THE SESSION FOR FLASH
778
4b4d3884 779As discussed in the previous chapter of the tutorial, C<flash> allows
780you to set variables in a way that is very similar to C<stash>, but it
781will remain set across multiple requests. Once the value is read, it
782is cleared (unless reset). Although C<flash> has nothing to do with
783authentication, it does leverage the same session plugins. Now that
784those plugins are enabled, let's go back and update the "delete and
785redirect with query parameters" code seen at the end of the L<Basic
786CRUD|Catalyst::Manual::Tutorial::BasicCRUD> chapter of the tutorial to
787take advantage of C<flash>.
d442cc9f 788
789First, open C<lib/MyApp/Controller/Books.pm> and modify C<sub delete>
3533daff 790to match the following (everything after the model search line of code
791has changed):
d442cc9f 792
905a3a26 793 =head2 delete
efdaddec 794
d442cc9f 795 Delete a book
efdaddec 796
d442cc9f 797 =cut
efdaddec 798
fbbb9084 799 sub delete :Chained('object') :PathPart('delete') :Args(0) {
800 my ($self, $c) = @_;
efdaddec 801
fbbb9084 802 # Use the book object saved by 'object' and delete it along
803 # with related 'book_authors' entries
804 $c->stash->{object}->delete;
efdaddec 805
d442cc9f 806 # Use 'flash' to save information across requests until it's read
807 $c->flash->{status_msg} = "Book deleted";
efdaddec 808
3533daff 809 # Redirect the user back to the list page
0416017e 810 $c->response->redirect($c->uri_for($self->action_for('list')));
d442cc9f 811 }
812
1390ef0e 813Next, open C<root/src/wrapper.tt2> and update the TT code to pull from
d442cc9f 814flash vs. the C<status_msg> query parameter:
815
1390ef0e 816 ...
d442cc9f 817 <div id="content">
1390ef0e 818 [%# Status and error messages %]
819 <span class="message">[% status_msg || c.flash.status_msg %]</span>
820 <span class="error">[% error_msg %]</span>
821 [%# This is where TT will stick all of your template's contents. -%]
822 [% content %]
823 </div><!-- end content -->
824 ...
905a3a26 825
636ba9f7 826Although the sample above only shows the C<content> div, leave the
1390ef0e 827rest of the file intact -- the only change we made to the C<wrapper.tt2>
636ba9f7 828was to add "C<|| c.request.params.status_msg>" to the
1390ef0e 829C<E<lt>span class="message"E<gt>> line.
d442cc9f 830
831
832=head2 Try Out Flash
833
636ba9f7 834Restart the development server, log in, and then point your browser to
835L<http://localhost:3000/books/url_create/Test/1/4> to create an extra
836several books. Click the "Return to list" link and delete one of the
837"Test" books you just added. The C<flash> mechanism should retain our
3533daff 838"Book deleted" status message across the redirect.
d442cc9f 839
840B<NOTE:> While C<flash> will save information across multiple requests,
841I<it does get cleared the first time it is read>. In general, this is
842exactly what you want -- the C<flash> message will get displayed on
843the next screen where it's appropriate, but it won't "keep showing up"
844after that first time (unless you reset it). Please refer to
845L<Catalyst::Plugin::Session|Catalyst::Plugin::Session> for additional
846information.
847
1390ef0e 848
3533daff 849=head2 Switch To Flash-To-Stash
850
636ba9f7 851Although the a use of flash above works well, the
1390ef0e 852C<status_msg || c.flash.status_msg> statement is a little ugly. A nice
905a3a26 853alternative is to use the C<flash_to_stash> feature that automatically
1390ef0e 854copies the content of flash to stash. This makes your controller
905a3a26 855and template code work regardless of where it was directly access, a
fbbb9084 856forward, or a redirect. To enable C<flash_to_stash>, you can either
905a3a26 857set the value in C<lib/MyApp.pm> by changing the default
3533daff 858C<__PACKAGE__-E<gt>config> setting to something like:
859
860 __PACKAGE__->config(
efdaddec 861 name => 'MyApp',
3533daff 862 session => {flash_to_stash => 1}
863 );
864
45d511e0 865B<or> add the following to C<myapp.conf>:
3533daff 866
45d511e0 867 <session>
868 flash_to_stash 1
869 </session>
3533daff 870
905a3a26 871The C<__PACKAGE__-E<gt>config> option is probably preferable here
872since it's not something you will want to change at runtime without it
3533daff 873possibly breaking some of your code.
874
1390ef0e 875Then edit C<root/src/wrapper.tt2> and change the C<status_msg> line
876to match the following:
3533daff 877
878 <span class="message">[% status_msg %]</span>
879
880Restart the development server and go to
905a3a26 881L<http://localhost:3000/books/list> in your browser. Delete another
3533daff 882of the "Test" books you added in the previous step. Flash should still
883maintain the status message across the redirect even though you are no
8a7c5151 884longer explicitly accessing C<c.flash>.
3533daff 885
d442cc9f 886
887=head1 AUTHOR
888
889Kennedy Clark, C<hkclark@gmail.com>
890
891Please report any errors, issues or suggestions to the author. The
892most recent version of the Catalyst Tutorial can be found at
82ab4bbf 893L<http://dev.catalyst.perl.org/repos/Catalyst/Catalyst-Manual/5.70/trunk/lib/Catalyst/Manual/Tutorial/>.
d442cc9f 894
45c7830f 895Copyright 2006-2008, Kennedy Clark, under Creative Commons License
95674086 896(L<http://creativecommons.org/licenses/by-sa/3.0/us/>).