Last active
August 29, 2015 14:06
-
-
Save bert2002/239ce332a6b7973bb324 to your computer and use it in GitHub Desktop.
Mojolicious with Facebook OAuth2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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