Commit | Line | Data |
4d583dd8 |
1 | =head1 NAME |
2 | |
64ccd8a8 |
3 | Catalyst::Manual::Tutorial::Authentication - Catalyst Tutorial - Part 4: Authentication |
4d583dd8 |
4 | |
5 | |
4d583dd8 |
6 | =head1 OVERVIEW |
7 | |
8 | This is B<Part 4 of 9> for the Catalyst tutorial. |
9 | |
64ccd8a8 |
10 | L<Tutorial Overview|Catalyst::Manual::Tutorial> |
4d583dd8 |
11 | |
12 | =over 4 |
13 | |
14 | =item 1 |
15 | |
16 | L<Introduction|Catalyst::Manual::Tutorial::Intro> |
17 | |
18 | =item 2 |
19 | |
20 | L<Catalyst Basics|Catalyst::Manual::Tutorial::CatalystBasics> |
21 | |
22 | =item 3 |
23 | |
978ca23d |
24 | L<Basic CRUD|Catalyst::Manual::Tutorial::BasicCRUD> |
4d583dd8 |
25 | |
26 | =item 4 |
27 | |
28 | B<Authentication> |
29 | |
30 | =item 5 |
31 | |
32 | L<Authorization|Catalyst::Manual::Tutorial::Authorization> |
33 | |
34 | =item 6 |
35 | |
36 | L<Debugging|Catalyst::Manual::Tutorial::Debugging> |
37 | |
38 | =item 7 |
39 | |
40 | L<Testing|Catalyst::Manual::Tutorial::Testing> |
41 | |
42 | =item 8 |
43 | |
44 | L<AdvancedCRUD|Catalyst::Manual::Tutorial::AdvancedCRUD> |
45 | |
46 | =item 9 |
47 | |
7d310f12 |
48 | L<Appendices|Catalyst::Manual::Tutorial::Appendices> |
4d583dd8 |
49 | |
50 | =back |
51 | |
52 | |
4d583dd8 |
53 | =head1 DESCRIPTION |
54 | |
64ccd8a8 |
55 | Now that we finally have a simple yet functional application, we can |
71dedf57 |
56 | focus on providing authentication (with authorization coming next in |
57 | Part 5). |
4d583dd8 |
58 | |
64ccd8a8 |
59 | This part of the tutorial is divided into two main sections: 1) basic, |
60 | cleartext authentication and 2) hash-based authentication. |
4d583dd8 |
61 | |
936a5dd5 |
62 | You can checkout the source code for this example from the catalyst |
63 | subversion repository as per the instructions in |
64 | L<Catalyst::Manual::Tutorial::Intro> |
4d583dd8 |
65 | |
4d583dd8 |
66 | =head1 BASIC AUTHENTICATION |
67 | |
71dedf57 |
68 | This section explores how to add authentication logic to a Catalyst |
69 | application. |
4d583dd8 |
70 | |
a63e6e67 |
71 | |
4d583dd8 |
72 | =head2 Add Users and Roles to the Database |
73 | |
71dedf57 |
74 | First, we add both user and role information to the database (we will |
75 | add the role information here although it will not be used until the |
64ccd8a8 |
76 | authorization section, Part 5). Create a new SQL script file by opening |
77 | C<myapp02.sql> in your editor and insert: |
4d583dd8 |
78 | |
79 | -- |
80 | -- Add users and roles tables, along with a many-to-many join table |
81 | -- |
82 | CREATE TABLE users ( |
83 | id INTEGER PRIMARY KEY, |
84 | username TEXT, |
85 | password TEXT, |
86 | email_address TEXT, |
87 | first_name TEXT, |
88 | last_name TEXT, |
89 | active INTEGER |
90 | ); |
91 | CREATE TABLE roles ( |
92 | id INTEGER PRIMARY KEY, |
93 | role TEXT |
94 | ); |
95 | CREATE TABLE user_roles ( |
96 | user_id INTEGER, |
97 | role_id INTEGER, |
98 | PRIMARY KEY (user_id, role_id) |
99 | ); |
100 | -- |
101 | -- Load up some initial test data |
102 | -- |
103 | INSERT INTO users VALUES (1, 'test01', 'mypass', 't01@na.com', 'Joe', 'Blow', 1); |
104 | INSERT INTO users VALUES (2, 'test02', 'mypass', 't02@na.com', 'Jane', 'Doe', 1); |
105 | INSERT INTO users VALUES (3, 'test03', 'mypass', 't03@na.com', 'No', 'Go', 0); |
106 | INSERT INTO roles VALUES (1, 'user'); |
107 | INSERT INTO roles VALUES (2, 'admin'); |
108 | INSERT INTO user_roles VALUES (1, 1); |
109 | INSERT INTO user_roles VALUES (1, 2); |
110 | INSERT INTO user_roles VALUES (2, 1); |
111 | INSERT INTO user_roles VALUES (3, 1); |
112 | |
113 | Then load this into the C<myapp.db> database with the following command: |
114 | |
115 | $ sqlite3 myapp.db < myapp02.sql |
116 | |
117 | |
71dedf57 |
118 | =head2 Add User and Role Information to DBIC Schema |
4d583dd8 |
119 | |
64ccd8a8 |
120 | This step adds DBIC-based classes for the user-related database tables |
71dedf57 |
121 | (the role information will not be used until Part 5): |
4d583dd8 |
122 | |
64ccd8a8 |
123 | Edit C<lib/MyAppDB.pm> and update the contents to match (only the |
124 | C<MyAppDB =E<gt> [qw/Book BookAuthor Author User UserRole Role/]> line |
125 | has changed): |
4d583dd8 |
126 | |
127 | package MyAppDB; |
128 | |
129 | =head1 NAME |
130 | |
131 | MyAppDB -- DBIC Schema Class |
132 | |
133 | =cut |
134 | |
135 | # Our schema needs to inherit from 'DBIx::Class::Schema' |
136 | use base qw/DBIx::Class::Schema/; |
137 | |
138 | # Need to load the DB Model classes here. |
139 | # You can use this syntax if you want: |
140 | # __PACKAGE__->load_classes(qw/Book BookAuthor Author User UserRole Role/); |
141 | # Also, if you simply want to load all of the classes in a directory |
142 | # of the same name as your schema class (as we do here) you can use: |
143 | # __PACKAGE__->load_classes(qw//); |
144 | # But the variation below is more flexible in that it can be used to |
145 | # load from multiple namespaces. |
146 | __PACKAGE__->load_classes({ |
147 | MyAppDB => [qw/Book BookAuthor Author User UserRole Role/] |
148 | }); |
149 | |
150 | 1; |
151 | |
152 | |
153 | =head2 Create New "Result Source Objects" |
154 | |
155 | Create the following three files with the content shown below. |
156 | |
157 | C<lib/MyAppDB/User.pm>: |
158 | |
159 | package MyAppDB::User; |
160 | |
161 | use base qw/DBIx::Class/; |
162 | |
163 | # Load required DBIC stuff |
164 | __PACKAGE__->load_components(qw/PK::Auto Core/); |
165 | # Set the table name |
166 | __PACKAGE__->table('users'); |
167 | # Set columns in table |
168 | __PACKAGE__->add_columns(qw/id username password email_address first_name last_name/); |
169 | # Set the primary key for the table |
170 | __PACKAGE__->set_primary_key('id'); |
171 | |
172 | # |
173 | # Set relationships: |
174 | # |
175 | |
176 | # has_many(): |
177 | # args: |
178 | # 1) Name of relationship, DBIC will create accessor with this name |
179 | # 2) Name of the model class referenced by this relationship |
180 | # 3) Column name in *foreign* table |
181 | __PACKAGE__->has_many(map_user_role => 'MyAppDB::UserRole', 'user_id'); |
182 | |
183 | |
184 | =head1 NAME |
185 | |
186 | MyAppDB::User - A model object representing a person with access to the system. |
187 | |
188 | =head1 DESCRIPTION |
189 | |
190 | This is an object that represents a row in the 'users' table of your application |
191 | database. It uses DBIx::Class (aka, DBIC) to do ORM. |
192 | |
193 | For Catalyst, this is designed to be used through MyApp::Model::MyAppDB. |
194 | Offline utilities may wish to use this class directly. |
195 | |
196 | =cut |
197 | |
198 | 1; |
199 | |
200 | |
201 | C<lib/MyAppDB/Role.pm>: |
202 | |
203 | package MyAppDB::Role; |
204 | |
205 | use base qw/DBIx::Class/; |
206 | |
207 | # Load required DBIC stuff |
208 | __PACKAGE__->load_components(qw/PK::Auto Core/); |
209 | # Set the table name |
210 | __PACKAGE__->table('roles'); |
211 | # Set columns in table |
212 | __PACKAGE__->add_columns(qw/id role/); |
213 | # Set the primary key for the table |
214 | __PACKAGE__->set_primary_key('id'); |
215 | |
216 | # |
217 | # Set relationships: |
218 | # |
219 | |
220 | # has_many(): |
221 | # args: |
222 | # 1) Name of relationship, DBIC will create accessor with this name |
223 | # 2) Name of the model class referenced by this relationship |
224 | # 3) Column name in *foreign* table |
225 | __PACKAGE__->has_many(map_user_role => 'MyAppDB::UserRole', 'role_id'); |
226 | |
227 | |
228 | =head1 NAME |
229 | |
230 | MyAppDB::Role - A model object representing a class of access permissions to |
231 | the system. |
232 | |
233 | =head1 DESCRIPTION |
234 | |
235 | This is an object that represents a row in the 'roles' table of your |
236 | application database. It uses DBIx::Class (aka, DBIC) to do ORM. |
237 | |
238 | For Catalyst, this is designed to be used through MyApp::Model::MyAppDB. |
239 | "Offline" utilities may wish to use this class directly. |
240 | |
241 | =cut |
242 | |
243 | 1; |
244 | |
245 | |
246 | C<lib/MyAppDB/UserRole.pm>: |
247 | |
248 | package MyAppDB::UserRole; |
249 | |
250 | use base qw/DBIx::Class/; |
251 | |
252 | # Load required DBIC stuff |
253 | __PACKAGE__->load_components(qw/PK::Auto Core/); |
254 | # Set the table name |
255 | __PACKAGE__->table('user_roles'); |
256 | # Set columns in table |
257 | __PACKAGE__->add_columns(qw/user_id role_id/); |
258 | # Set the primary key for the table |
259 | __PACKAGE__->set_primary_key(qw/user_id role_id/); |
260 | |
261 | # |
262 | # Set relationships: |
263 | # |
264 | |
265 | # belongs_to(): |
266 | # args: |
267 | # 1) Name of relationship, DBIC will create accessor with this name |
268 | # 2) Name of the model class referenced by this relationship |
269 | # 3) Column name in *this* table |
270 | __PACKAGE__->belongs_to(user => 'MyAppDB::User', 'user_id'); |
271 | |
272 | # belongs_to(): |
273 | # args: |
274 | # 1) Name of relationship, DBIC will create accessor with this name |
275 | # 2) Name of the model class referenced by this relationship |
276 | # 3) Column name in *this* table |
277 | __PACKAGE__->belongs_to(role => 'MyAppDB::Role', 'role_id'); |
278 | |
279 | |
280 | =head1 NAME |
281 | |
282 | MyAppDB::UserRole - A model object representing the JOIN between Users and Roles. |
283 | |
284 | =head1 DESCRIPTION |
285 | |
286 | This is an object that represents a row in the 'user_roles' table of your application |
287 | database. It uses DBIx::Class (aka, DBIC) to do ORM. |
288 | |
289 | You probably won't need to use this class directly -- it will be automatically |
290 | used by DBIC where joins are needed. |
291 | |
292 | For Catalyst, this is designed to be used through MyApp::Model::MyAppDB. |
293 | Offline utilities may wish to use this class directly. |
294 | |
295 | =cut |
296 | |
297 | 1; |
298 | |
299 | The code for these three result source classes is obviously very familiar to the C<Book>, C<Author>, and C<BookAuthor> classes created in Part 2. |
300 | |
301 | |
302 | =head2 Sanity-Check Reload of Development Server |
303 | |
304 | 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 C<Ctrl-C> to kill the previous server instance (if it's still running) and restart it: |
305 | |
306 | $ script/myapp_server.pl |
307 | |
308 | Look for the three new model objects in the startup debug output: |
309 | |
310 | ... |
311 | .-------------------------------------------------------------------+----------. |
312 | | Class | Type | |
313 | +-------------------------------------------------------------------+----------+ |
314 | | MyApp::Controller::Books | instance | |
315 | | MyApp::Controller::Root | instance | |
316 | | MyApp::Model::MyAppDB | instance | |
317 | | MyApp::Model::MyAppDB::Author | class | |
318 | | MyApp::Model::MyAppDB::Book | class | |
319 | | MyApp::Model::MyAppDB::BookAuthor | class | |
320 | | MyApp::Model::MyAppDB::Role | class | |
321 | | MyApp::Model::MyAppDB::User | class | |
322 | | MyApp::Model::MyAppDB::UserRole | class | |
323 | | MyApp::View::TT | instance | |
324 | '-------------------------------------------------------------------+----------' |
325 | ... |
326 | |
327 | Again, notice that your "result source" classes have been "re-loaded" by Catalyst under C<MyApp::Model>. |
328 | |
329 | |
330 | =head2 Include Authentication and Session Plugins |
331 | |
33aee7ed |
332 | Edit C<lib/MyApp.pm> and update it as follows (everything below C<StackTrace> is new): |
4d583dd8 |
333 | |
334 | use Catalyst qw/ |
335 | -Debug |
336 | ConfigLoader |
337 | Static::Simple |
338 | |
4d583dd8 |
339 | StackTrace |
4d583dd8 |
340 | |
341 | Authentication |
342 | Authentication::Store::DBIC |
343 | Authentication::Credential::Password |
344 | |
345 | Session |
346 | Session::Store::FastMmap |
347 | Session::State::Cookie |
348 | /; |
349 | |
64ccd8a8 |
350 | The three C<Authentication> plugins work together to support |
351 | Authentication while the C<Session> plugins are required to maintain |
352 | state across multiple HTTP requests. Note that there are several |
a63e6e67 |
353 | options for L<Session::Store|Catalyst::Plugin::Session::Store> |
354 | (L<Session::Store::FastMmap|Catalyst::Plugin::Session::Store::FastMmap> |
64ccd8a8 |
355 | is generally a good choice if you are on Unix; try |
356 | L<Cache::FileCache|Catalyst::Plugin::Cache::FileCache> if you are on |
357 | Win32) -- consult L<Session::Store|Catalyst::Plugin::Session::Store> and |
358 | its subclasses for additional information. |
4d583dd8 |
359 | |
a63e6e67 |
360 | |
4d583dd8 |
361 | =head2 Configure Authentication |
362 | |
64ccd8a8 |
363 | Although C<__PACKAGE__-E<gt>config(name =E<gt> 'value');> is still |
364 | supported, newer Catalyst applications tend to place all configuration |
365 | information in C<myapp.yml> and automatically load this information into |
a63e6e67 |
366 | C<MyApp-E<gt>config> using the |
367 | L<ConfigLoader|Catalyst::Plugin::ConfigLoader> plugin. Here, we need |
368 | to load several parameters that tell |
369 | L<Catalyst::Plugin::Authentication|Catalyst::Plugin::Authentication> |
370 | where to locate information in your database. To do this, edit the |
371 | C<myapp.yml> YAML and update it to match: |
4d583dd8 |
372 | |
373 | --- |
374 | name: MyApp |
375 | authentication: |
376 | dbic: |
377 | # Note this first definition would be the same as setting |
378 | # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User' |
379 | # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file). |
380 | # |
381 | # This is the model object created by Catalyst::Model::DBIC from your |
382 | # schema (you created 'MyAppDB::User' but as the Catalyst startup |
383 | # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User'). |
a63e6e67 |
384 | # NOTE: Omit 'MyApp::Model' to avoid a component lookup issue in Catalyst 5.66 |
4d583dd8 |
385 | user_class: MyAppDB::User |
386 | # This is the name of the field in your 'users' table that contains the user's name |
387 | user_field: username |
388 | # This is the name of the field in your 'users' table that contains the password |
389 | password_field: password |
390 | # Other options can go here for hashed passwords |
391 | |
392 | Inline comments in the code above explain how each field is being used. |
393 | |
64ccd8a8 |
394 | B<TIP>: Although YAML uses a very simple and easy-to-ready format, it |
395 | does require the use of a consistent level of indenting. Be sure you |
396 | line up everything on a given 'level' with the same number of indents. |
397 | Also, be sure not to use C<tab> characters (YAML does not support them |
398 | because they are handled inconsistently across editors). |
4d583dd8 |
399 | |
a63e6e67 |
400 | |
4d583dd8 |
401 | =head2 Add Login and Logout Controllers |
402 | |
403 | Use the Catalyst create script to create two stub controller files: |
404 | |
405 | $ script/myapp_create.pl controller Login |
406 | $ script/myapp_create.pl controller Logout |
407 | |
64ccd8a8 |
408 | B<NOTE>: You could easily use a single controller here. For example, |
409 | you could have a C<User> controller with both C<login> and C<logout> |
410 | actions. Remember, Catalyst is designed to be very flexible, and leaves |
411 | such matters up to you, the designer and programmer. |
4d583dd8 |
412 | |
be16bacd |
413 | Then open C<lib/MyApp/Controller/Login.pm>, locate the C<sub index : |
414 | Private> method (this was automatically inserted by the helpers when we |
415 | created the Login controller above), and delete this line: |
416 | |
417 | $c->response->body('Matched MyApp::Controller::Login in Login.'); |
418 | |
419 | Then update it to match: |
4d583dd8 |
420 | |
7d310f12 |
421 | =head2 index |
4d583dd8 |
422 | |
423 | Login logic |
424 | |
425 | =cut |
426 | |
be16bacd |
427 | sub index : Private { |
4d583dd8 |
428 | my ($self, $c) = @_; |
429 | |
430 | # Get the username and password from form |
431 | my $username = $c->request->params->{username} || ""; |
432 | my $password = $c->request->params->{password} || ""; |
433 | |
434 | # If the username and password values were found in form |
435 | if ($username && $password) { |
436 | # Attempt to log the user in |
437 | if ($c->login($username, $password)) { |
438 | # If successful, then let them use the application |
439 | $c->response->redirect($c->uri_for('/books/list')); |
440 | return; |
441 | } else { |
442 | # Set an error message |
443 | $c->stash->{error_msg} = "Bad username or password."; |
444 | } |
445 | } |
446 | |
447 | # If either of above don't work out, send to the login page |
448 | $c->stash->{template} = 'login.tt2'; |
449 | } |
450 | |
64ccd8a8 |
451 | This controller fetches the C<username> and C<password> values from the |
452 | login form and attempts to perform a login. If successful, it redirects |
453 | the user to the book list page. If the login fails, the user will stay |
454 | at the login page but receive an error message. If the C<username> and |
455 | C<password> values are not present in the form, the user will be taken |
456 | to the empty login form. |
4d583dd8 |
457 | |
7e5eb02c |
458 | Note that we could have used something like C<sub default :Private>; |
459 | however, the use of C<default> actions is discouraged because it does |
460 | not receive path args as with other actions. The recommended practice |
461 | is to only use C<default> in C<MyApp::Controller::Root>. |
462 | |
8112f931 |
463 | Another option would be to use something like |
be16bacd |
464 | C<sub base :Path :Args(0) {...}> (where the C<...> refers to the login |
465 | code shown in C<sub index : Private> above). We are using C<sub base |
466 | :Path :Args(0) {...}> here to specifically match the URL C</login>. |
467 | C<Path> actions (aka, "literal actions") create URI matches relative to |
468 | the namespace of the controller where they are defined. Although |
469 | C<Path> supports arguments that allow relative and absolute paths to be |
470 | defined, here we use an empty C<Path> definition to match on just the |
471 | name of the controller itself. The method name, C<base>, is arbitrary. |
472 | We make the match even more specific with the C<:Args(0)> action |
473 | modifier -- this forces the match on I<only> C</login>, not |
474 | C</login/somethingelse>. |
475 | |
7d310f12 |
476 | Next, update the corresponding method in C<lib/MyApp/Controller/Logout.pm> |
477 | to match: |
4d583dd8 |
478 | |
7d310f12 |
479 | =head2 index |
4d583dd8 |
480 | |
481 | Logout logic |
482 | |
483 | =cut |
484 | |
be16bacd |
485 | sub index : Private { |
4d583dd8 |
486 | my ($self, $c) = @_; |
487 | |
488 | # Clear the user's state |
489 | $c->logout; |
490 | |
71dedf57 |
491 | # Send the user to the starting point |
4d583dd8 |
492 | $c->response->redirect($c->uri_for('/')); |
493 | } |
494 | |
be16bacd |
495 | As with the login controller, be sure to delete the |
496 | C<$c->response->body('Matched MyApp::Controller::Logout in Logout.');> |
497 | line of the C<sub index>. |
7e5eb02c |
498 | |
4d583dd8 |
499 | |
500 | =head2 Add a Login Form TT Template Page |
501 | |
502 | Create a login form by opening C<root/src/login.tt2> and inserting: |
503 | |
504 | [% META title = 'Login' %] |
505 | |
506 | <!-- Login form --> |
507 | <form method="post" action=" [% Catalyst.uri_for('/login') %] "> |
508 | <table> |
509 | <tr> |
510 | <td>Username:</td> |
511 | <td><input type="text" name="username" size="40" /></td> |
512 | </tr> |
513 | <tr> |
514 | <td>Password:</td> |
515 | <td><input type="password" name="password" size="40" /></td> |
516 | </tr> |
517 | <tr> |
518 | <td colspan="2"><input type="submit" name="submit" value="Submit" /></td> |
519 | </tr> |
520 | </table> |
521 | </form> |
522 | |
523 | |
524 | =head2 Add Valid User Check |
525 | |
64ccd8a8 |
526 | We need something that provides enforcement for the authentication |
527 | mechanism -- a I<global> mechanism that prevents users who have not |
528 | passed authentication from reaching any pages except the login page. |
529 | This is generally done via an C<auto> action/method (prior to Catalyst |
530 | v5.66, this sort of thing would go in C<MyApp.pm>, but starting in |
531 | v5.66, the preferred location is C<lib/MyApp/Controller/Root.pm>). |
4d583dd8 |
532 | |
71dedf57 |
533 | Edit the existing C<lib/MyApp/Controller/Root.pm> class file and insert |
534 | the following method: |
4d583dd8 |
535 | |
536 | =head2 auto |
537 | |
538 | Check if there is a user and, if not, forward to login page |
539 | |
540 | =cut |
541 | |
542 | # Note that 'auto' runs after 'begin' but before your actions and that |
543 | # 'auto' "chain" (all from application path to most specific class are run) |
d0afb3a9 |
544 | # See the 'Actions' section of 'Catalyst::Manual::Intro' for more info. |
4d583dd8 |
545 | sub auto : Private { |
546 | my ($self, $c) = @_; |
547 | |
23645266 |
548 | # Allow unauthenticated users to reach the login page. This |
549 | # allows anauthenticated users to reach any action in the Login |
550 | # controller. To lock it down to a single action, we could use: |
551 | # if ($c->action eq $c->controller('Login')->action_for('index')) |
552 | # to only allow unauthenticated access to the C<index> action we |
553 | # added above. |
554 | if ($c->controller eq $c->controller('Login')) { |
4d583dd8 |
555 | return 1; |
556 | } |
557 | |
558 | # If a user doesn't exist, force login |
559 | if (!$c->user_exists) { |
560 | # Dump a log message to the development server debug output |
561 | $c->log->debug('***Root::auto User not found, forwarding to /login'); |
562 | # Redirect the user to the login page |
563 | $c->response->redirect($c->uri_for('/login')); |
564 | # Return 0 to cancel 'post-auto' processing and prevent use of application |
565 | return 0; |
566 | } |
567 | |
568 | # User found, so return 1 to continue with processing after this 'auto' |
569 | return 1; |
570 | } |
571 | |
64ccd8a8 |
572 | B<Note:> Catalyst provides a number of different types of actions, such |
573 | as C<Local>, C<Regex>, and C<Private>. You should refer to |
71dedf57 |
574 | L<Catalyst::Manual::Intro> for a more detailed explanation, but the |
575 | following bullet points provide a quick introduction: |
4d583dd8 |
576 | |
577 | =over 4 |
578 | |
579 | =item * |
580 | |
64ccd8a8 |
581 | The majority of application use C<Local> actions for items that respond |
582 | to user requests and C<Private> actions for those that do not directly |
583 | respond to user input. |
4d583dd8 |
584 | |
585 | =item * |
586 | |
64ccd8a8 |
587 | There are five types of C<Private> actions: C<begin>, C<end>, |
588 | C<default>, C<index>, and C<auto>. |
4d583dd8 |
589 | |
590 | =item * |
591 | |
d0afb3a9 |
592 | With C<begin>, C<end>, C<default>, C<index> private actions, only the |
593 | most specific action of each type will be called. For example, if you |
594 | define a C<begin> action in your controller it will I<override> a |
595 | C<begin> action in your application/root controller -- I<only> the |
596 | action in your controller will be called. |
597 | |
598 | =item * |
599 | |
a63e6e67 |
600 | Unlike the other actions where only a single method is called for each |
601 | request, I<every> auto action along the chain of namespaces will be |
d0afb3a9 |
602 | called. Each C<auto> action will be called I<from the application/root |
603 | controller down through the most specific class>. |
4d583dd8 |
604 | |
605 | =back |
606 | |
64ccd8a8 |
607 | By placing the authentication enforcement code inside the C<auto> method |
608 | of C<lib/MyApp/Controller/Root.pm> (or C<lib/MyApp.pm>), it will be |
609 | called for I<every> request that is received by the entire application. |
4d583dd8 |
610 | |
a63e6e67 |
611 | |
4d583dd8 |
612 | =head2 Displaying Content Only to Authenticated Users |
613 | |
64ccd8a8 |
614 | Let's say you want to provide some information on the login page that |
615 | changes depending on whether the user has authenticated yet. To do |
616 | this, open C<root/src/login.tt2> in your editor and add the following |
617 | lines to the bottom of the file: |
4d583dd8 |
618 | |
619 | <p> |
620 | [% |
621 | # This code illustrates how certain parts of the TT |
622 | # template will only be shown to users who have logged in |
623 | %] |
240f9371 |
624 | [% IF Catalyst.user_exists %] |
4d583dd8 |
625 | Please Note: You are already logged in as '[% Catalyst.user.username %]'. |
626 | You can <a href="[% Catalyst.uri_for('/logout') %]">logout</a> here. |
627 | [% ELSE %] |
628 | You need to log in to use this application. |
629 | [% END %] |
630 | [%# |
631 | Note that this whole block is a comment because the "#" appears |
632 | immediate after the "[%" (with no spaces in between). Although it |
633 | can be a handy way to temporarily "comment out" a whole block of |
634 | TT code, it's probably a little too subtle for use in "normal" |
635 | comments. |
636 | %] |
637 | |
64ccd8a8 |
638 | Although most of the code is comments, the middle few lines provide a |
639 | "you are already logged in" reminder if the user returns to the login |
640 | page after they have already authenticated. For users who have not yet |
641 | authenticated, a "You need to log in..." message is displayed (note the |
642 | use of an IF-THEN-ELSE construct in TT). |
4d583dd8 |
643 | |
644 | |
645 | =head2 Try Out Authentication |
646 | |
64ccd8a8 |
647 | Press C<Ctrl-C> to kill the previous server instance (if it's still |
648 | running) and restart it: |
4d583dd8 |
649 | |
650 | $ script/myapp_server.pl |
651 | |
64ccd8a8 |
652 | B<IMPORTANT NOTE>: If you happen to be using Internet Explorer, you may |
653 | need to use the command C<script/myapp_server.pl -k> to enable the |
654 | keepalive feature in the development server. Otherwise, the HTTP |
655 | redirect on successful login may not work correctly with IE (it seems to |
656 | work without -k if you are running the web browser and development |
657 | server on the same machine). If you are using browser a browser other |
658 | than IE, it should work either way. If you want to make keepalive the |
659 | default, you can edit C<script/myapp_server.pl> and change the |
660 | initialization value for C<$keepalive> to C<1>. (You will need to do |
661 | this every time you create a new Catalyst application or rebuild the |
662 | C<myapp_server.pl> script.) |
663 | |
664 | Now trying going to L<http://localhost:3000/books/list> and you should |
665 | be redirected to the login page, hitting Shift+Reload if necessary (the |
666 | "You are already logged in" message should I<not> appear -- if it does, |
71dedf57 |
667 | click the C<logout> button and try again). Note the C<***Root::auto User |
668 | not found...> debug message in the development server output. Enter |
669 | username C<test01> and password C<mypass>, and you should be taken to |
670 | the Book List page. |
4d583dd8 |
671 | |
71dedf57 |
672 | Open C<root/src/books/list.tt2> and add the following lines to the |
673 | bottom: |
4d583dd8 |
674 | |
675 | <p> |
676 | <a href="[% Catalyst.uri_for('/login') %]">Login</a> |
677 | <a href="[% Catalyst.uri_for('form_create') %]">Create</a> |
678 | </p> |
679 | |
be16bacd |
680 | Reload your browser and you should now see a "Login" and "Create" links |
681 | at the bottom of the page (as mentioned earlier, you can update template |
682 | files without reloading the development server). Click the first link |
683 | to return to the login page. This time you I<should> see the "You are |
684 | already logged in" message. |
4d583dd8 |
685 | |
64ccd8a8 |
686 | Finally, click the C<You can logout here> link on the C</login> page. |
687 | You should stay at the login page, but the message should change to "You |
688 | need to log in to use this application." |
4d583dd8 |
689 | |
690 | |
4d583dd8 |
691 | =head1 USING PASSWORD HASHES |
692 | |
64ccd8a8 |
693 | In this section we increase the security of our system by converting |
694 | from cleartext passwords to SHA-1 password hashes. |
4d583dd8 |
695 | |
64ccd8a8 |
696 | B<Note:> This section is optional. You can skip it and the rest of the |
697 | tutorial will function normally. |
4d583dd8 |
698 | |
64ccd8a8 |
699 | Note that even with the techniques shown in this section, the browser |
700 | still transmits the passwords in cleartext to your application. We are |
701 | just avoiding the I<storage> of cleartext passwords in the database by |
71dedf57 |
702 | using a SHA-1 hash. If you are concerned about cleartext passwords |
703 | between the browser and your application, consider using SSL/TLS, made |
978ca23d |
704 | easy with the Catalyst plugin Catalyst::Plugin:RequireSSL. |
a63e6e67 |
705 | |
4d583dd8 |
706 | |
707 | =head2 Get a SHA-1 Hash for the Password |
708 | |
64ccd8a8 |
709 | Catalyst uses the C<Digest> module to support a variety of hashing |
710 | algorithms. Here we will use SHA-1 (SHA = Secure Hash Algorithm). |
711 | First, we should compute the SHA-1 hash for the "mypass" password we are |
712 | using. The following command-line Perl script provides a "quick and |
713 | dirty" way to do this: |
4d583dd8 |
714 | |
715 | $ perl -MDigest::SHA -e 'print Digest::SHA::sha1_hex("mypass"), "\n"' |
716 | e727d1464ae12436e899a726da5b2f11d8381b26 |
717 | $ |
718 | |
cc548726 |
719 | B<Note:> You should probably modify this code for production use to |
720 | not read the password from the command line. By having the script |
721 | prompt for the cleartext password, it avoids having the password linger |
722 | in forms such as your C<.bash_history> files (assuming you are using |
723 | BASH as your shell). An example of such a script can be found in |
724 | Appendix 3. |
725 | |
a63e6e67 |
726 | |
4d583dd8 |
727 | =head2 Switch to SHA-1 Password Hashes in the Database |
728 | |
64ccd8a8 |
729 | Next, we need to change the C<password> column of our C<users> table to |
730 | store this hash value vs. the existing cleartext password. Open |
731 | C<myapp03.sql> in your editor and enter: |
4d583dd8 |
732 | |
733 | -- |
734 | -- Convert passwords to SHA-1 hashes |
735 | -- |
736 | UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 1; |
737 | UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 2; |
738 | UPDATE users SET password = 'e727d1464ae12436e899a726da5b2f11d8381b26' WHERE id = 3; |
739 | |
740 | Then use the following command to update the SQLite database: |
741 | |
742 | $ sqlite3 myapp.db < myapp03.sql |
743 | |
64ccd8a8 |
744 | B<Note:> We are using SHA-1 hashes here, but many other hashing |
745 | algorithms are supported. See C<Digest> for more information. |
4d583dd8 |
746 | |
a63e6e67 |
747 | |
64ccd8a8 |
748 | =head2 Enable SHA-1 Hash Passwords in |
749 | C<Catalyst::Plugin::Authentication::Store::DBIC> |
4d583dd8 |
750 | |
64ccd8a8 |
751 | Edit C<myapp.yml> and update it to match (the C<password_type> and |
752 | C<password_hash_type> are new, everything else is the same): |
4d583dd8 |
753 | |
754 | --- |
755 | name: MyApp |
756 | authentication: |
757 | dbic: |
758 | # Note this first definition would be the same as setting |
759 | # __PACKAGE__->config->{authentication}->{dbic}->{user_class} = 'MyAppDB::User' |
760 | # in lib/MyApp.pm (IOW, each hash key becomes a "name:" in the YAML file). |
761 | # |
762 | # This is the model object created by Catalyst::Model::DBIC from your |
763 | # schema (you created 'MyAppDB::User' but as the Catalyst startup |
764 | # debug messages show, it was loaded as 'MyApp::Model::MyAppDB::User'). |
23645266 |
765 | # NOTE: Omit 'MyApp::Model' here just as you would when using |
766 | # '$c->model("MyAppDB::User)' |
4d583dd8 |
767 | user_class: MyAppDB::User |
768 | # This is the name of the field in your 'users' table that contains the user's name |
769 | user_field: username |
770 | # This is the name of the field in your 'users' table that contains the password |
771 | password_field: password |
772 | # Other options can go here for hashed passwords |
773 | # Enabled hashed passwords |
774 | password_type: hashed |
775 | # Use the SHA-1 hashing algorithm |
776 | password_hash_type: SHA-1 |
777 | |
778 | |
779 | =head2 Try Out the Hashed Passwords |
780 | |
64ccd8a8 |
781 | Press C<Ctrl-C> to kill the previous server instance (if it's still |
782 | running) and restart it: |
4d583dd8 |
783 | |
784 | $ script/myapp_server.pl |
785 | |
64ccd8a8 |
786 | You should now be able to go to L<http://localhost:3000/books/list> and |
787 | login as before. When done, click the "Logout" link on the login page |
788 | (or point your browser at L<http://localhost:3000/logout>). |
4d583dd8 |
789 | |
be16bacd |
790 | B<Note:> If you receive the debug screen in your browser with a |
791 | C<Can't call method "stash" on an undefined value...> error message, |
792 | make sure that you are using v0.07 of |
793 | L<Catalyst::Plugin::Authorization::ACL|Catalyst::Plugin::Authorization::ACL>. |
794 | The following command can be a useful way to quickly dump the version number |
795 | of this module on your system: |
796 | |
797 | perl -MCatalyst::Plugin::Authorization::ACL -e 'print $Catalyst::Plugin::Authorization::ACL::VERSION, "\n";' |
798 | |
a63e6e67 |
799 | |
4d583dd8 |
800 | =head1 AUTHOR |
801 | |
802 | Kennedy Clark, C<hkclark@gmail.com> |
803 | |
eed93301 |
804 | Please report any errors, issues or suggestions to the author. The |
7d310f12 |
805 | most recent version of the Catalyst Tutorial can be found at |
eed93301 |
806 | L<http://dev.catalyst.perl.org/repos/Catalyst/trunk/Catalyst-Runtime/lib/Catalyst/Manual/Tutorial/>. |
4d583dd8 |
807 | |
a63e6e67 |
808 | Copyright 2006, Kennedy Clark, under Creative Commons License |
809 | (L<http://creativecommons.org/licenses/by-nc-sa/2.5/>). |