updated 'Require user logins' example to use new Auth framework; added example for...
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Manual / Cookbook.pod
index 2cfdf77..a39e607 100644 (file)
@@ -40,45 +40,15 @@ statistics in your debug messages.
 =head2 Scaffolding
 
 Scaffolding is very simple with Catalyst.
-Just use Catalyst::Model::CDBI::CRUD as your base class.
 
-    # lib/MyApp/Model/CDBI.pm
-    package MyApp::Model::CDBI;
+The recommended way is to use Catalyst::Helper::Controller::Scaffold.
 
-    use strict;
-    use base 'Catalyst::Model::CDBI::CRUD';
-
-    __PACKAGE__->config(
-        dsn           => 'dbi:SQLite:/tmp/myapp.db',
-        relationships => 1
-    );
-
-    1;
-
-    # lib/MyApp.pm
-    package MyApp;
-
-    use Catalyst 'FormValidator';
-
-    __PACKAGE__->config(
-        name => 'My Application',
-        root => '/home/joeuser/myapp/root'
-    );
+Just install this module, and to scaffold a Class::DBI Model class, do the following:
 
-    sub my_table : Global {
-        my ( $self, $c ) = @_;
-        $c->form( optional => [ MyApp::Model::CDBI::Table->columns ] );
-        $c->forward('MyApp::Model::CDBI::Table');
-    }
+./script/myapp_create controller <name> Scaffold <CDBI::Class>Scaffolding
 
-    1;
 
-Modify the C<$c-E<gt>form()> parameters to match your needs, and don't
-forget to copy the templates into the template root. Can't find the
-templates?  They were in the CRUD model distribution, so you can do
-B<look Catalyst::Model::CDBI::CRUD> from the CPAN shell to find them.
 
-Other Scaffolding modules are in development at the time of writing.
 
 =head2 File uploads
 
@@ -629,7 +599,7 @@ C<end> method; see L<Catalyst::Plugin::FillInForm>).
             $c->stash->{errors}   = $c->error;
             $c->stash->{template} = 'errors.tt';
             $c->forward('MyApp::View::TT');
-            $c->{error} = [];
+            $c->error(0);
         }
     
         return 1 if $c->response->status =~ /^3\d\d$/;
@@ -646,6 +616,164 @@ You can manually set errors in your code to trigger this page by calling
 
     $c->error( 'You broke me!' );
 
+=head2 Require user logins
+
+It's often useful to restrict access to your application to a set of
+registered users, forcing everyone else to the login page until they're
+signed in.
+
+To implement this in your application make sure you have a customer
+table with username and password fields and a corresponding Model class
+in your Catalyst application, then make the following changes:
+
+=head3 lib/MyApp.pm
+
+  use Catalyst qw/
+      Authentication
+      Authentication::Store::DBIC
+      Authentication::Credential::Password
+  /;
+
+  __PACKAGE__->config->{authentication}->{dbic} = {
+    'user_class'        => 'My::Model::DBIC::User',
+    'user_field'        => 'username',
+    'password_field'    => 'password'
+    'password_type'     => 'hashed',
+    'password_hash_type'=> 'SHA-1'
+  };
+
+  sub auto : Private {
+    my ($self, $c) = @_;
+    my $login_path = 'user/login';
+
+    # allow people to actually reach the login page!
+    if ($c->request->path eq $login_path) {
+      return 1;
+    }
+
+    # if a user doesn't exist, force login
+    if ( !$c->user_exists ) {
+      # force the login screen to be shown
+      $c->response->redirect($c->request->base . $login_path);
+    }
+
+    # otherwise, we have a user - continue with the processing chain
+    return 1;
+  }
+
+=head3 lib/MyApp/C/User.pm
+
+  sub login : Path('/user/login') {
+    my ($self, $c) = @_;
+
+    # default template
+    $c->stash->{'template'} = "user/login.tt";
+    # default form message
+    $c->stash->{'message'} = 'Please enter your username and password';
+
+    if ( $c->request->param('username') ) {
+      # try to log the user in
+      # login() is provided by ::Authentication::Credential::Password
+      if( $c->login(
+        $c->request->param('username'),
+        $c->request->param('password'),
+        );
+        
+        # if login() returns 1, user is now logged in
+        $c->response->redirect('/some/page');
+      }
+
+      # otherwise we failed to login, try again!
+      $c->stash->{'message'} = 
+         'Unable to authenticate the login details supplied';
+    }
+  }
+
+  sub logout : Path('/user/logout') {
+    my ($self, $c) = @_;
+    # log the user out
+    $c->logout;
+
+    # do the 'default' action
+    $c->response->redirect($c->request->base);
+  }
+
+
+=head3 root/base/user/login.tt
+
+ [% INCLUDE header.tt %]
+ <form action="/user/login" method="POST" name="login_form">
+    [% message %]<br />
+    <label for="username">username:</label><br />
+    <input type="text" id="username" name="username" /><br />
+
+    <label for="password">password:</label><br />
+    <input type="password" id="password" name="password" /><br />
+
+    <input type="submit" value="log in" name="form_submit" />
+  </form>
+  [% INCLUDE footer.tt %]
+
+=head2 Role-based Authorization
+
+For more advanced access control, you may want to consider using role-based
+authorization. This means you can assign different roles to each user, e.g.
+"user", "admin", etc.
+
+The C<login> and C<logout> methods and view template are exactly the same as
+in the previous example.
+
+The L<Catalyst::Plugin::Authorization::Roles> plugin is required when
+implementing roles:
+
+ use Catalyst qw/
+    Authentication
+    Authentication::Credential::Password
+    Authentication::Store::Htpasswd
+    Authorization::Roles
+  /;
+
+Roles are implemented automatically when using
+L<Catalyst::Authetication::Store::Htpasswd>:
+
+  # no additional role configuration required
+  __PACKAGE__->config->{authentication}{htpasswd} = "passwdfile";
+
+Or can be set up manually when using L<Catalyst::Authentication::Store::DBIC>:
+
+  # Authorization using a many-to-many role relationship
+  __PACKAGE__->config->{authorization}{dbic} = {
+    'role_class'           => 'My::Model::DBIC::Role',
+    'role_field'           => 'name',
+    'user_role_user_field' => 'user',
+
+    # DBIx::Class only (omit if using Class::DBI)
+    'role_rel'             => 'user_role',
+
+    # Class::DBI only, (omit if using DBIx::Class)
+    'user_role_class'      => 'My::Model::CDBI::UserRole'
+    'user_role_role_field' => 'role',
+  };
+
+To restrict access to any action, you can use the C<check_user_roles> method:
+
+  sub restricted : Local {
+     my ( $self, $c ) = @_;
+
+     $c->detach("unauthorized")
+       unless $c->check_user_roles( "admin" );
+
+     # do something restricted here
+  }
+
+You can also use the C<assert_user_roles> method. This just gives an error if
+the current user does not have one of the required roles:
+
+  sub also_restricted : Global {
+    my ( $self, $c ) = @_;
+    $c->assert_user_roles( qw/ user admin / );
+  }
+
 =head1 AUTHOR
 
 Sebastian Riedel, C<sri@oook.de>
@@ -655,6 +783,7 @@ Marcus Ramberg, C<mramberg@cpan.org>
 Jesse Sheidlower, C<jester@panix.com>
 Andy Grundman, C<andy@hybridized.org> 
 Chisel Wright, C<pause@herlpacker.co.uk>
+Will Hawes, C<info@whawes.co.uk>
 
 =head1 COPYRIGHT