Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Mojolicious with Facebook OAuth2
#!/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
<!DOCTYPE html>
<html>
<body><%= content %></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment