In order to add Facebook login to your Catalyst applications (in this example MyApp) you will need the following modules from CPAN (add them to your Makefile.PL):
requires 'Catalyst::Authentication::Credential::Facebook::OAuth2'; requires 'Facebook::Graph';
Add facebook realm in your application config or MyApp.pm:
'Plugin::Authentication' => { default_realm => 'localdb', localdb => { credential => { class => 'Password', password_field => 'password', password_type => 'self_check', }, store => { class => 'DBIx::Class', user_model => 'DB::User', role_relation => 'roles', role_field => 'role_name', #use_userdata_from_session => '1', } }, facebook => { credential => { class => 'Facebook::OAuth2', application_id => '****************', application_secret => '****************', }, } },
Of course put in application_id and application_secret the settings defined for your app in Facebook application settings on https://developers.facebook.com/apps. Also make sure you test your application from the domain you defined there.
Next create the login action for Facebook for example in Root.pm controller, let’s call it fblogin:
sub fblogin : Path('/fblogin') : Args(0) { my ( $self, $c ) = @_; my $fblogin = $c->authenticate({ scope => ['offline_access', 'publish_stream'], }, 'facebook'); if (defined $fblogin) { # use Facebook::Graph to get user info from login token my $fb = Facebook::Graph->new; $fb->access_token($fblogin->{token}); my $fbuser = $fb->fetch('me'); my $user; eval { # try to find the user in your local DB by email (make sure is unique) $user = $c->find_user({ email => $fbuser->{'email'} }, 'localdb'); }; if (defined $user) { # found the user in local DB, authenticate $c->set_authenticated($user, 'localdb'); } # now you have the logged in user in $c->user $c->stash->{user} = $c->user->obj; $c->response->redirect( $c->uri_for( '/' ) ); } }
By accessing /fblogin on your application, you will be redirected to a login page on Facebook and after successful authentication back to your application url with authentication token present. If the user is already logged in to Facebook, you can achieve one click login to your application.
Leave a comment