Mojolicious mit Facebook OAuth2

Ich wollte mich einmal ein bisschen mit dem Graphen von Facebook und Authentifizierung mittels OAuth2 per Facebook schlau machen und bin dabei über den Blog Eintrag bei tudorconstantin.com gestoßen. Genaueres steht auf der Seite, jedoch ist der Code nicht sofort einsetzbar und habe ich ein mal korrigiert:

#!/usr/bin/env perl
use Mojolicious::Lite;
use Net::Facebook::Oauth2;

my $config = {
  facebook => {
      app_id => '',
      secret => '',
      redirect_url => 'http://mojo.dev:3000/redirect_from_fb',
    },
};

plugin 'o_auth2', {
  facebook => {
    key    => $config->{facebook}->{app_id},
    secret => $config->{facebook}->{secret},
}};

get '/' => sub {
  my $self = shift;

  $self->redirect_to('authenticate') unless $self->session->{user}->{fb_username};
  return $self->render('index_authenticated');
  
} => 'index';

get authenticate => sub {
  my $self = shift;

  my $url = $self->get_authorize_url(
    'facebook',
    scope => 'offline_access publish_stream user_likes email',
    redirect_uri => $config->{facebook}->{redirect_url},
  );

  $self->redirect_to( $url->to_abs->to_string );
} => 'authenticate';

get redirect_from_fb => sub {
  my $self = shift;
  my $token = $self->param('code');

  my $fb = Net::Facebook::Oauth2->new(
    application_id     => $config->{facebook}->{app_id},
    application_secret => $config->{facebook}->{secret},
    access_token       => $token,
    callback           => $config->{facebook}->{redirect_url}
  );

	my $access_token = $fb->get_access_token(code => $token);

	$fb = Net::Facebook::Oauth2->new(
		access_token => $access_token
  );

	my $info = $fb->get(
		'https://graph.facebook.com/me'
  );
							    
  print $info->as_json;

  $self->session->{user} = {
	    fb_username   => $info->as_hash->{name},
  };

  $self->redirect_to('index');
} => 'redirect_from_fb';

app->start;
__DATA__

@@ index_unauthenticated.html.ep
% layout 'default';

<%= link_to 'Click here to authenticate with FB' => 'authenticate'; %>

@@ index_authenticated.html.ep
% layout 'default';

Hello <%= session->{user}->{fb_username} %>

<%= link_to 'Click here to authenticate with FB' => 'authenticate'; %>

@@ layouts/default.html.ep
<%= content %>

oder auf gist.github.com.

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.