This is 0.16 on the way up to the CPAN.
[catagits/Catalyst-Authentication-Credential-OpenID.git] / lib / Catalyst / Authentication / Credential / OpenID.pm
index 307cbd0..de9a9f3 100644 (file)
@@ -1,18 +1,15 @@
 package Catalyst::Authentication::Credential::OpenID;
+use strict;
+# use warnings; no warnings "uninitialized"; # for testing, not production
 use parent "Class::Accessor::Fast";
 
 BEGIN {
     __PACKAGE__->mk_accessors(qw/ _config realm debug secret /);
 }
 
-use strict;
-use warnings;
-no warnings "uninitialized";
-
-our $VERSION = "0.02";
+our $VERSION = "0.16";
 
 use Net::OpenID::Consumer;
-use UNIVERSAL::require;
 use Catalyst::Exception ();
 
 sub new : method {
@@ -35,14 +32,15 @@ sub new : method {
                                                             );
 
     $secret = substr($secret,0,255) if length $secret > 255;
-    $self->secret( $secret );
-    $self->_config->{ua_class} ||= "LWPx::ParanoidAgent";
+    $self->secret($secret);
+    # If user has no preference we prefer L::PA b/c it can prevent DoS attacks.
+    $self->_config->{ua_class} ||= eval "use LWPx::ParanoidAgent" ?
+        "LWPx::ParanoidAgent" : "LWP::UserAgent";
 
-    eval {
-        $self->_config->{ua_class}->require;
-    }
-    or Catalyst::Exception->throw("Could not 'require' user agent class " .
-                                  $self->_config->{ua_class});
+    my $agent_class = $self->_config->{ua_class};
+    eval "require $agent_class"
+        or Catalyst::Exception->throw("Could not 'require' user agent class " .
+                                      $self->_config->{ua_class});
 
     $c->log->debug("Setting consumer secret: " . $secret) if $self->debug;
 
@@ -62,18 +60,42 @@ sub authenticate : method {
     $claimed_uri ||= $c->req->method eq 'GET' ? 
         $c->req->query_params->{ $field } : $c->req->body_params->{ $field };
 
+
     my $csr = Net::OpenID::Consumer->new(
         ua => $self->_config->{ua_class}->new(%{$self->_config->{ua_args} || {}}),
         args => $c->req->params,
         consumer_secret => $self->secret,
     );
 
+    if ( $self->_config->{extension_args} and $self->debug )
+    {
+        $c->log->info("The configuration key 'extension_args' is deprecated; use 'extensions'");
+    }
+
+    my @extensions = $self->_config->{extensions} ?
+        @{ $self->_config->{extensions} } : $self->_config->{extension_args} ?
+        @{ $self->_config->{extension_args} } : ();
+
     if ( $claimed_uri )
     {
         my $current = $c->uri_for($c->req->uri->path); # clear query/fragment...
 
-        my $identity = $csr->claimed_identity($claimed_uri)
-            or Catalyst::Exception->throw($csr->err);
+        my $identity = $csr->claimed_identity($claimed_uri);
+        unless ( $identity )
+        {
+            if ( $self->_config->{errors_are_fatal} )
+            {
+                Catalyst::Exception->throw($csr->err);
+            }
+            else
+            {
+                $c->log->error($csr->err . " -- $claimed_uri");
+                $c->detach();
+            }
+        }
+
+        $identity->set_extension_args(@extensions)
+            if @extensions;
 
         my $check_url = $identity->check_url(
             return_to  => $current . '?openid-check=1',
@@ -81,7 +103,7 @@ sub authenticate : method {
             delayed_return => 1,
         );
         $c->res->redirect($check_url);
-        return;
+        $c->detach();
     }
     elsif ( $c->req->params->{'openid-check'} )
     {
@@ -99,6 +121,12 @@ sub authenticate : method {
             # This is where we ought to build an OpenID user and verify against the spec.
             my $user = +{ map { $_ => scalar $identity->$_ }
                 qw( url display rss atom foaf declared_rss declared_atom declared_foaf foafmaker ) };
+            # Dude, I did not design the array as hash spec. Don't curse me [apv].
+            my %flat = @extensions;
+            for my $key ( keys %flat )
+            {
+                $user->{extensions}->{$key} = $identity->signed_extension_fields($key);
+            }
 
             my $user_obj = $realm->find_user($user, $c);
 
@@ -108,35 +136,49 @@ sub authenticate : method {
             }
             else
             {
-                $c->log->debug("Verified OpenID identity failed to load with find_user; bad user_class? Try 'Null.'") if $c->debug;
+                $c->log->debug("Verified OpenID identity failed to load with find_user; bad user_class? Try 'Null.'") if $self->debug;
                 return;
             }
         }
         else
         {
-            Catalyst::Exception->throw("Error validating identity: " .
-                                       $csr->err);
+            $self->_config->{errors_are_fatal} ?
+                Catalyst::Exception->throw("Error validating identity: " . $csr->err)
+                      :
+                $c->log->error( $csr->err);
         }
     }
-    else
-    {
-        return;
-    }
+    return;
 }
 
 1;
 
 __END__
 
-=pod
-
 =head1 NAME
 
-Catalyst::Authentication::Credential::OpenID - OpenID credential for L<Catalyst::Plugin::Authentication> framework.
+Catalyst::Authentication::Credential::OpenID - OpenID credential for Catalyst::Plugin::Authentication framework.
+
+=head1 VERSION
+
+0.16
+
+=head1 BACKWARDS COMPATIBILITY CHANGES
+
+=head2 EXTENSION_ARGS v EXTENSIONS
+
+B<NB>: The extensions were previously configured under the key C<extension_args>. They are now configured under C<extensions>. This prevents the need for double configuration but it breaks extensions in your application if you do not change the name. The old version is supported for now but may be phased out at any time.
+
+As previously noted, L</EXTENSIONS TO OPENID>, I have not tested the extensions. I would be grateful for any feedback or, better, tests.
+
+=head2 FATALS
+
+The problems encountered by failed OpenID operations have always been fatals in the past. This is unexpected behavior for most users as it differs from other credentials. Authentication errors here are no longer fatal. Debug/error output is improved to offset the loss of information. If for some reason you would prefer the legacy/fatal behavior, set the configuration variable C<errors_are_fatal> to a true value.
 
 =head1 SYNOPSIS
 
- # MyApp
+In MyApp.pm-
+
  use Catalyst qw/
     Authentication
     Session
@@ -144,15 +186,32 @@ Catalyst::Authentication::Credential::OpenID - OpenID credential for L<Catalyst:
     Session::State::Cookie
  /;
 
- # MyApp.yaml --
+Somewhere in myapp.conf-
+
+ <Plugin::Authentication>
+     default_realm   openid
+     <realms>
+         <openid>
+             <credential>
+                 class   OpenID
+                 ua_class   LWP::UserAgent
+             </credential>
+         </openid>
+     </realms>
+ </Plugin::Authentication>
+
+Or in your myapp.yml if you're using L<YAML> instead-
+
  Plugin::Authentication:
    default_realm: openid
    realms:
      openid:
        credential:
          class: OpenID
+         ua_class: LWP::UserAgent
+
+In a controller, perhaps C<Root::openid>-
 
- # Root::openid().
  sub openid : Local {
       my($self, $c) = @_;
 
@@ -167,32 +226,32 @@ Catalyst::Authentication::Credential::OpenID - OpenID credential for L<Catalyst:
       }
  }
 
- # openid.tt
+And a L<Template> to match in C<openid.tt>-
+
  <form action="[% c.uri_for('/openid') %]" method="GET" name="openid">
  <input type="text" name="openid_identifier" class="openid" />
  <input type="submit" value="Sign in with OpenID" />
  </form>
 
-
 =head1 DESCRIPTION
 
 This is the B<third> OpenID related authentication piece for
-L<Catalyst>. The first -- L<Catalyst::Plugin::Authentication::OpenID>
-by Benjamin Trott -- was deprecated by the second --
+L<Catalyst>. The first E<mdash> L<Catalyst::Plugin::Authentication::OpenID>
+by Benjamin Trott E<mdash> was deprecated by the second E<mdash>
 L<Catalyst::Plugin::Authentication::Credential::OpenID> by Tatsuhiko
-Miyagawa -- and this is an attempt to deprecate both by conforming to
+Miyagawa E<mdash> and this is an attempt to deprecate both by conforming to
 the newish, at the time of this module's inception, realm-based
 authentication in L<Catalyst::Plugin::Authentication>.
 
- * Catalyst::Plugin::Authentication::OpenID (first)
- * Catalyst::Plugin::Authentication::Credential::OpenID (second)
- * Catalyst::Authentication::Credential::OpenID (this, the third)
+ 1. Catalyst::Plugin::Authentication::OpenID
+ 2. Catalyst::Plugin::Authentication::Credential::OpenID
+ 3. Catalyst::Authentication::Credential::OpenID
 
 The benefit of this version is that you can use an arbitrary number of
 authentication systems in your L<Catalyst> application and configure
 and call all of them in the same way.
 
-Note, both earlier versions of OpenID authentication use the method
+Note that both earlier versions of OpenID authentication use the method
 C<authenticate_openid()>. This module uses C<authenticate()> and
 relies on you to specify the realm. You can specify the realm as the
 default in the configuration or inline with each
@@ -202,11 +261,11 @@ This module functions quite differently internally from the others.
 See L<Catalyst::Plugin::Authentication::Internals> for more about this
 implementation.
 
-=head1 METHOD
+=head1 METHODS
 
 =over 4
 
-=item * $c->authenticate({},"your_openid_realm");
+=item $c->authenticate({},"your_openid_realm");
 
 Call to authenticate the user via OpenID. Returns false if
 authorization is unsuccessful. Sets the user into the session and
@@ -224,7 +283,7 @@ It implicitly does this (sort of, it checks the request method too)-
  my $claimed_uri = $c->req->params->{openid_identifier};
  $c->authenticate({openid_identifier => $claimed_uri});
 
-=item * Catalyst::Authentication::Credential::OpenID->new()
+=item Catalyst::Authentication::Credential::OpenID->new()
 
 You will never call this. Catalyst does it for you. The only important
 thing you might like to know about it is that it merges its realm
@@ -239,23 +298,23 @@ Currently the only supported user class is L<Catalyst::Plugin::Authentication::U
 
 =over 4
 
-=item * $c->user->url
+=item $c->user->url
 
-=item * $c->user->display
+=item $c->user->display
 
-=item * $c->user->rss 
+=item $c->user->rss 
 
-=item * $c->user->atom
+=item $c->user->atom
 
-=item * $c->user->foaf
+=item $c->user->foaf
 
-=item * $c->user->declared_rss
+=item $c->user->declared_rss
 
-=item * $c->user->declared_atom
+=item $c->user->declared_atom
 
-=item * $c->user->declared_foaf
+=item $c->user->declared_foaf
 
-=item * $c->user->foafmaker
+=item $c->user->foafmaker
 
 =back
 
@@ -294,23 +353,74 @@ clear text passwords and one called "openid" which uses... uh, OpenID.
                           }
               },
               openid => {
-                  consumer_secret => "Don't bother setting",
-                  ua_class => "LWPx::ParanoidAgent",
-                  ua_args => {
-                      whitelisted_hosts => [qw/ 127.0.0.1 localhost /],
-                  },
                   credential => {
                       class => "OpenID",
                       store => {
                           class => "OpenID",
                       },
+                      consumer_secret => "Don't bother setting",
+                      ua_class => "LWP::UserAgent",
+                      # whitelist is only relevant for LWPx::ParanoidAgent
+                      ua_args => {
+                          whitelisted_hosts => [qw/ 127.0.0.1 localhost /],
+                      },
+                      extensions => [
+                          'http://openid.net/extensions/sreg/1.1',
+                          {
+                           required => 'email',
+                           optional => 'fullname,nickname,timezone',
+                          },
+                      ],
                   },
               },
           },
-      },
-      );
+      }
+    );
 
-And now, the same configuration in YAML.
+This is the same configuration in the default L<Catalyst> configuration format from L<Config::General>.
+
+ name   MyApp
+ <Plugin::Authentication>
+     default_realm   members
+     <realms>
+         <members>
+             <store>
+                 class   Minimal
+                 <users>
+                     <paco>
+                         password   l4s4v3n7ur45
+                     </paco>
+                 </users>
+             </store>
+             <credential>
+                 password_field   password
+                 password_type   clear
+                 class   Password
+             </credential>
+         </members>
+         <openid>
+             <credential>
+                 <store>
+                     class   OpenID
+                 </store>
+                 class   OpenID
+                 <ua_args>
+                     whitelisted_hosts   127.0.0.1
+                     whitelisted_hosts   localhost
+                 </ua_args>
+                 consumer_secret   Don't bother setting
+                 ua_class   LWP::UserAgent
+                 <extensions>
+                     http://openid.net/extensions/sreg/1.1
+                     required   email
+                     optional   fullname,nickname,timezone
+                 </extensions>
+             </credential>
+         </openid>
+     </realms>
+ </Plugin::Authentication>
+
+And now, the same configuration in L<YAML>. B<NB>: L<YAML> is whitespace sensitive.
 
  name: MyApp
  Plugin::Authentication:
@@ -331,106 +441,107 @@ And now, the same configuration in YAML.
          class: OpenID
          store:
            class: OpenID
-       consumer_secret: Don't bother setting
-       ua_class: LWPx::ParanoidAgent
-       ua_args:
-         whitelisted_hosts:
-           - 127.0.0.1
-           - localhost
+         consumer_secret: Don't bother setting
+         ua_class: LWP::UserAgent
+         ua_args:
+           # whitelist is only relevant for LWPx::ParanoidAgent
+           whitelisted_hosts:
+             - 127.0.0.1
+             - localhost
+         extensions:
+             - http://openid.net/extensions/sreg/1.1
+             - required: email
+               optional: fullname,nickname,timezone
 
-B<NB>: There is no OpenID store yet. Trying for next release.
+B<NB>: There is no OpenID store yet.
 
-=head1 CONFIGURATION
+=head2 EXTENSIONS TO OPENID
 
-These are set in your realm. See above.
+The Simple Registration--L<http://openid.net/extensions/sreg/1.1>--(SREG) extension to OpenID is supported in the L<Net::OpenID> family now. Experimental support for it is included here as of v0.12. SREG is the only supported extension in OpenID 1.1. It's experimental in the sense it's a new interface and barely tested. Support for OpenID extensions is here to stay.
+
+=head2 MORE ON CONFIGURATION
 
 =over 4
 
-=item * ua_args and ua_class
+=item ua_args and ua_class
 
-L<LWPx::ParanoidAgent> is the default agent -- C<ua_class>. You don't
-have to set it. I recommend that you do B<not> override it. You can
-with any well behaved L<LWP::UserAgent>. You probably should not.
-L<LWPx::ParanoidAgent> buys you many defenses and extra security
-checks. When you allow your application users freedom to initiate
-external requests, you open a big avenue for DoS (denial of service)
-attacks. L<LWPx::ParanoidAgent> defends against this.
-L<LWP::UserAgent> and any regular subclass of it will not.
+L<LWPx::ParanoidAgent> is the default agent E<mdash> C<ua_class> E<mdash> if it's available, L<LWP::UserAgent> if not. You don't have to set
+it. I recommend that you do B<not> override it. You can with any well behaved L<LWP::UserAgent>. You probably should not.
+L<LWPx::ParanoidAgent> buys you many defenses and extra security checks. When you allow your application users freedom to initiate external
+requests, you open an avenue for DoS (denial of service) attacks. L<LWPx::ParanoidAgent> defends against this. L<LWP::UserAgent> and any
+regular subclass of it will not.
 
-=item * consumer_secret
+=item consumer_secret
 
-The underlying L<Net::OpenID::Consumer> object is seeded with a
-secret. If it's important to you to set your own, you can. The default
-uses this package name + its version + the sorted configuration keys
-of your Catalyst application (chopped at 255 characters if it's
-longer). This should generally be superior to any fixed string.
+The underlying L<Net::OpenID::Consumer> object is seeded with a secret. If it's important to you to set your own, you can. The default uses
+this package name + its version + the sorted configuration keys of your Catalyst application (chopped at 255 characters if it's longer).
+This should generally be superior to any fixed string.
 
 =back
 
-
 =head1 TODO
 
-There are some interesting implications with this sort of setup. Does
-a user aggregate realms or can a user be signed in under more than one
-realm? The documents could contain a recipe of the self-answering
-OpenID end-point that is in the tests.
+Option to suppress fatals.
+
+Support more of the new methods in the L<Net::OpenID> kit.
 
-Debug statements need to be both expanded and limited via realm
-configuration.
+There are some interesting implications with this sort of setup. Does a user aggregate realms or can a user be signed in under more than one
+realm? The documents could contain a recipe of the self-answering OpenID end-point that is in the tests.
+
+Debug statements need to be both expanded and limited via realm configuration.
 
 Better diagnostics in errors. Debug info at all consumer calls.
 
 Roles from provider domains? Mapped? Direct? A generic "openid" auto_role?
 
-=head1 LICENSE AND COPYRIGHT
+=head1 THANKS
 
-Copyright (c) 2008, Ashley Pond V C<< <ashley@cpan.org> >>. Some of
-Tatsuhiko Miyagawa's work is reused here.
+To Benjamin Trott (L<Catalyst::Plugin::Authentication::OpenID>), Tatsuhiko Miyagawa (L<Catalyst::Plugin::Authentication::Credential::OpenID>), Brad Fitzpatrick for the great OpenID stuff, Martin Atkins for picking up the code to handle OpenID 2.0, and Jay Kuri and everyone else who has made Catalyst such a wonderful framework.
 
-This module is free software; you can redistribute it and modify it
-under the same terms as Perl itself. See L<perlartistic>.
+Menno Blom provided a bug fix and the hook to use OpenID extensions.
 
+=head1 LICENSE AND COPYRIGHT
+
+Copyright (c) 2008-2009, Ashley Pond V C<< <ashley@cpan.org> >>. Some of Tatsuhiko Miyagawa's work is reused here.
+
+This module is free software; you can redistribute it and modify it under the same terms as Perl itself. See L<perlartistic>.
 
 =head1 DISCLAIMER OF WARRANTY
 
-Because this software is licensed free of charge, there is no warranty
-for the software, to the extent permitted by applicable law. Except when
-otherwise stated in writing the copyright holders and other parties
-provide the software "as is" without warranty of any kind, either
-expressed or implied, including, but not limited to, the implied
-warranties of merchantability and fitness for a particular purpose. The
-entire risk as to the quality and performance of the software is with
-you. Should the software prove defective, you assume the cost of all
+Because this software is licensed free of charge, there is no warranty for the software, to the extent permitted by applicable law. Except
+when otherwise stated in writing the copyright holders and other parties provide the software "as is" without warranty of any kind, either
+expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The
+entire risk as to the quality and performance of the software is with you. Should the software prove defective, you assume the cost of all
 necessary servicing, repair, or correction.
 
-In no event unless required by applicable law or agreed to in writing
-will any copyright holder, or any other party who may modify or
-redistribute the software as permitted by the above license, be
-liable to you for damages, including any general, special, incidental,
-or consequential damages arising out of the use or inability to use
-the software (including but not limited to loss of data or data being
-rendered inaccurate or losses sustained by you or third parties or a
-failure of the software to operate with any other software), even if
-such holder or other party has been advised of the possibility of
-such damages.
+In no event unless required by applicable law or agreed to in writing will any copyright holder, or any other party who may modify or
+redistribute the software as permitted by the above license, be liable to you for damages, including any general, special, incidental, or
+consequential damages arising out of the use or inability to use the software (including but not limited to loss of data or data being
+rendered inaccurate or losses sustained by you or third parties or a failure of the software to operate with any other software), even if
+such holder or other party has been advised of the possibility of such damages.
+
+=head1 SEE ALSO
 
+=over 4
 
-=head1 THANKS
+=item OpenID
 
-To Benjamin Trott, Tatsuhiko Miyagawa, and Brad Fitzpatrick for the
-great OpenID stuff and to Jay Kuri and everyone else who has made
-Catalyst such a wonderful framework.
+L<Net::OpenID::Server>, L<Net::OpenID::VerifiedIdentity>, L<Net::OpenID::Consumer>, L<http://openid.net/>,
+L<http://openid.net/developers/specs/>, and L<http://openid.net/extensions/sreg/1.1>.
 
-=head1 SEE ALSO
+=item Catalyst Authentication
 
-L<Catalyst>, L<Catalyst::Plugin::Authentication>,
-L<Net::OpenID::Consumer>, and L<LWPx::ParanoidAgent>.
+L<Catalyst>, L<Catalyst::Plugin::Authentication>, L<Catalyst::Manual::Tutorial::Authorization>, and
+L<Catalyst::Manual::Tutorial::Authentication>.
 
-=head2 RELATED
+=item Catalyst Configuration
 
-L<Net::OpenID::Server>, L<Net::OpenID::VerifiedIdentity>,
-L<http://openid.net/>, and L<http://openid.net/developers/specs/>.
+L<Catalyst::Plugin::ConfigLoader>, L<Config::General>, and L<YAML>.
 
-L<Catalyst::Plugin::Authentication::OpenID> (Benjamin Trott) and L<Catalyst::Plugin::Authentication::Credential::OpenID> (Tatsuhiko Miyagawa).
+=item Miscellaneous
+
+L<Catalyst::Manual::Tutorial>, L<Template>, L<LWPx::ParanoidAgent>.
+
+=back
 
 =cut