Net-Facebook-Oauth2-0.12/0000755000175000017500000000000013615640370014012 5ustar mamodmamodNet-Facebook-Oauth2-0.12/META.yml0000664000175000017500000000170713615640370015272 0ustar mamodmamod--- abstract: 'a simple Perl wrapper around Facebook OAuth 2.0 protocol' author: - 'Mahmoud A. Mehyar ' build_requires: Plack::Loader: '0' Plack::Request: '0' Test::Exception: '0' Test::MockModule: '0' Test::MockObject: '0' Test::More: '0.88' Test::Requires: '0' Test::TCP: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.0401, CPAN::Meta::Converter version 2.150001' license: unknown meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Net-Facebook-Oauth2 no_index: directory: - t - inc requires: Carp: '0' JSON::MaybeXS: '0' LWP::Protocol::https: '0' LWP::UserAgent: '0' URI: '0' URI::Escape: '0' resources: bugtracker: https://github.com/mamod/Net-Facebook-Oauth2/issues license: http://dev.perl.org/licenses/ repository: https://github.com/mamod/Net-Facebook-Oauth2 version: '0.12' Net-Facebook-Oauth2-0.12/examples/0000755000175000017500000000000013615640370015630 5ustar mamodmamodNet-Facebook-Oauth2-0.12/examples/CGI/0000755000175000017500000000000013615640370016232 5ustar mamodmamodNet-Facebook-Oauth2-0.12/examples/CGI/facebook.pl0000644000175000017500000000672713615636414020360 0ustar mamodmamod#!/usr/bin/perl use strict; use warnings; use CGI; use Net::Facebook::Oauth2; use Data::Dumper; =head1 DESCRIPTION This is a general example of using use Net::Facebook::Oauth2; For a better understanding I recommend you to look at the Catalyst example Don't worry if you are not familiar with catalyst, I tried to make it as simple as I can with no complication, plus Catalyst is awsome :) =cut sub facebook { my $cgi = CGI->new; my $fb = Net::Facebook::Oauth2->new( application_id => 'your_application_id', ##get this from your facebook developers platform application_secret => 'your_application_secret', ##get this from your facebook developers platform callback => 'http://your-domain.com/callback', ##Callback URL, facebook will redirect users after authintication ); ##you can find more about facebook scopes/Extended Permissions at ##http://developers.facebook.com/docs/authentication/permissions my $url = $fb->get_authorization_url( scope => ['user_posts','manage_pages', 'user_friends'], ###pass scope/Extended Permissions params as an array telling facebook how you want to use this access display => 'page' ## how to display authorization page, other options popup "to display as popup window" and wab "for mobile apps" ); ##now redirect to the authorization page print $cgi->redirect($url); } sub callback { ##this sub represent the callback block, where facebook will send users back upon authorization my $cgi = CGI->new; my $fb = Net::Facebook::Oauth2->new( application_id => 'your_application_id', application_secret => 'your_application_secret', callback => 'http://your-domain.com/callback' ); ####We recieve "verifier" code parameter, now get access token ###you need to pass the verifier code to get access_token my $access_token = $fb->get_access_token(code => $cgi->param('code')); ##that's it, now you have access_token of this user ###save this token in database or session to use later in your application save_access_token($access_token); print $cgi->header(); print "Welcome"; } ###get information about this user from Facebook, use get method sub get { my $cgi = CGI->new; ###now any time you want to get information about user, just retrieve saved access_token of that use ###pass it to ###and call facebook Graph API URL ###for example let's get friends list of that user my $access_token = get_access_token('userid'); ###this is a demo, no real get_access_token sub here :P my $fb = Net::Facebook::Oauth2->new( access_token => $access_token ##Load previous saved access token from session or database ); my $friends = $fb->get( 'https://graph.facebook.com/v2.8/me/friends' ##Facebook friends list API URL ); print $cgi->header(); print $friends->as_json; } ###to post something to facebook use post method sub post { my $cgi = CGI->new; ###Lets post a message to the feed of the authorized user my $access_token = get_access_token('userid'); my $fb = Net::Facebook::Oauth2->new( access_token => $access_token ); my $res = $fb->post( 'https://graph.facebook.com/v2.8/me/feed', ###API URL { message => 'This is a post to my feed from Net::Facebook::Oauth2' ##hash of params/variables (param=>value) } ); print $cgi->header(); print Dumper($res->as_hash); ##print response as perl hash } 1; Net-Facebook-Oauth2-0.12/examples/Catalyst/0000755000175000017500000000000013615640370017414 5ustar mamodmamodNet-Facebook-Oauth2-0.12/examples/Catalyst/Facebook.pm0000644000175000017500000000776113615636414021502 0ustar mamodmamodpackage MyApp::Controller::Facebook; use strict; use warnings; use parent 'Catalyst::Controller'; use Net::Facebook::Oauth2; =head1 DESCRIPTION this example shows you how to use Net::Facebook::Oauth2 with Catalyst, it's not the best way of writing your catalyst controller though :P The call back URL below is in the same block of When live test this application don't use localhost, as facebook will return an error because the callback URL must match the one you set in facebook developer platfor for your application =cut sub index : Private { my ( $self, $c ) = @_; my $params = $c->req->parameters; my $fb = Net::Facebook::Oauth2->new( application_id => 'your_application_id', ##get this from your facebook developers platform application_secret => 'your_application_secret', ##get this from your facebook developers platform callback => 'http://localhost:3000/facebook', ##Callback URL, facebook will redirect users after authintication ); #### first check if callback URL doesn't contain a verifier code "code" parameter if (!$params->{code}){ ##there is no verifier code passed so let's create authorization URL and redirect to it my $url = $fb->get_authorization_url( scope => ['user_posts','manage_pages', 'user_friends'], ###pass scope/Extended Permissions params as an array telling facebook how you want to use this access display => 'page' ## how to display authorization page, other options popup "to display as popup window" and wab "for mobile apps" ); ##you can find more about facebook scopes/Extended Permissions at ##http://developers.facebook.com/docs/authentication/permissions $c->res->redirect($url); } else { ####second step, we recieved "verifier" code parameters, now get access token ###you need to pass the verifier code to get access_token my $access_token = $fb->get_access_token( code => $params->{code} ); ###save this token in database or session $c->session->{access_token} = $access_token; $c->res->body('Welcome from facebook'); } } ##get/post to facebook on the behalf of the authorized user ##first get this user information, login name, user profile URL sub get : Local { my ( $self, $c ) = @_; my $params = $c->req->parameters; my $fb = Net::Facebook::Oauth2->new( access_token => $c->session->{access_token} ##Load previous saved access token from session or database ); ##lets get list of friends for the authorized user my $info = $fb->get( 'https://graph.facebook.com/v2.8/me' ##Facebook API URL ); $c->res->body($info->as_json); ##as_json method will print response as json object } ##example 2 - get friends list for this user sub get_friends : Local { my ( $self, $c ) = @_; my $params = $c->req->parameters; my $fb = Net::Facebook::Oauth2->new( access_token => $c->session->{access_token} ); ##lets get list of friends for the authorized user my $friends = $fb->get( 'https://graph.facebook.com/v2.8/me/friends' ##Facebook 'list friend' Graph API URL ); $c->res->body($friends->as_json); } ####post to facebook example sub post : Local { my ( $self, $c ) = @_; my $params = $c->req->parameters; ###Lets post a message to the feed of the authorized user my $fb = Net::Facebook::Oauth2->new( access_token => $c->session->{access_token} ); my $res = $fb->post( 'https://graph.facebook.com/v2.8/me/feed', ###API URL { message => 'This is a post to my feed from Net::Facebook::Oauth2' ##hash of params/variables (param=>value) } ); $c->res->body($res->as_json); } 1; Net-Facebook-Oauth2-0.12/MANIFEST.SKIP0000644000175000017500000000014213615636414015711 0ustar mamodmamodMYMETA.json MYMETA.yml pm_to_blib blib Makefile$ \.*tar.gz$ \.tmp$ \.old$ \.bak$ \.git.+ \.travis Net-Facebook-Oauth2-0.12/lib/0000755000175000017500000000000013615640370014560 5ustar mamodmamodNet-Facebook-Oauth2-0.12/lib/Net/0000755000175000017500000000000013615640370015306 5ustar mamodmamodNet-Facebook-Oauth2-0.12/lib/Net/Facebook/0000755000175000017500000000000013615640370017017 5ustar mamodmamodNet-Facebook-Oauth2-0.12/lib/Net/Facebook/Oauth2.pm0000644000175000017500000005345013615640012020517 0ustar mamodmamodpackage Net::Facebook::Oauth2; use strict; use warnings; use LWP::UserAgent; use URI; use URI::Escape; use JSON::MaybeXS; use Carp; our $VERSION = '0.12'; sub new { my ($class,%options) = @_; my $self = {}; $self->{options} = \%options; my $api_version = defined $options{api_version} ? $options{api_version} : 'v4.0'; if (!defined $options{access_token}){ croak "You must provide your application id in new()\nNet::Facebook::Oauth2->new( application_id => '...' )" unless defined $self->{options}->{application_id}; croak "You must provide your application secret in new()\nNet::Facebook::Oauth2->new( application_secret => '...' )" unless defined $self->{options}->{application_secret}; } if (defined $options{access_token_url}) { croak "cannot pass access_token_url AND api_version" if defined $options{api_version}; $self->{access_token_url} = $options{access_token_url}; } else { $self->{access_token_url} = "https://graph.facebook.com/$api_version/oauth/access_token"; } if (defined $options{authorize_url}) { croak "cannot pass authorize_url AND api_version" if defined $options{api_version}; $self->{authorize_url} = $options{authorize_url}; } else { $self->{authorize_url} = "https://www.facebook.com/$api_version/dialog/oauth"; } if (defined $options{debug_token_url}) { croak "cannot pass debug_token_url AND api_version" if defined $options{api_version}; $self->{debug_token_url} = $options{debug_token_url}; } else { $self->{debug_token_url} = "https://graph.facebook.com/$api_version/debug_token"; } $self->{browser} = $options{browser} || LWP::UserAgent->new; $self->{display} = $options{display} || 'page'; ## other values popup and wab $self->{access_token} = $options{access_token}; return bless($self, $class); } sub get_authorization_url { my ($self,%params) = @_; $params{callback} ||= $self->{options}->{callback}; croak "You must pass a callback parameter with Oauth v2.0" unless defined $params{callback}; $params{display} = $self->{display} unless defined $params{display}; $self->{options}->{callback} = $params{callback}; my $url = $self->{authorize_url} ."?client_id=" .uri_escape($self->{options}->{application_id}) ."&redirect_uri=" .uri_escape($params{callback}); if ($params{scope}) { my $scope = join(',', @{$params{scope}}); $url .= '&scope=' . $scope if $scope; } # state is now required: $url .= '&state=' . (defined $params{state} ? $params{state} : time); $url .= '&response_type=' . $params{response_type} if $params{response_type}; $url .= '&auth_type=' . $params{auth_type} if $params{auth_type}; $url .= "&display=".$params{display}; return $url; } sub get_access_token { my ($self,%params) = @_; $params{callback} ||= $self->{options}->{callback}; $params{code} ||= $self->{options}->{code}; croak "You must pass a code parameter with Oauth v2.0" unless defined $params{code}; croak "You must pass callback URL" unless defined $params{callback}; $self->{options}->{code} = $params{code}; ###generating access token URL my $getURL = $self->{access_token_url} ."?client_id=" .uri_escape($self->{options}->{application_id}) ."&redirect_uri=" .uri_escape($params{callback}) ."&client_secret=" .uri_escape($self->{options}->{application_secret}) ."&code=$params{code}"; my $response = $self->{browser}->get($getURL); my $json = decode_json($response->content()); if (!$response->is_success || exists $json->{error}){ ##got an error response from facebook. die and display error message croak "'" . $json->{error}->{type}. "'" . " " .$json->{error}->{message}; } elsif ($json->{access_token}) { ##everything is ok proccess response and extract access token return $self->{access_token} = $json->{access_token}; } else { croak "can't get access token from " . $response->content(); } } sub get_long_lived_token { my ($self,%params) = @_; if (!$self->{access_token}) { croak "You must pass the access_token" unless defined $params{access_token}; } my $getURL = $self->{access_token_url} . '?grant_type=fb_exchange_token' . '&client_id=' . uri_escape($self->{options}->{application_id}) . '&client_secret=' . uri_escape($self->{options}->{application_secret}) . '&fb_exchange_token=' . uri_escape($self->{access_token} || $params{access_token}) ; my $response = $self->{browser}->get($getURL); my $json = decode_json($response->content()); if (!$response->is_success || exists $json->{error}) { croak "'" . $json->{error}->{type}. "'" . " " .$json->{error}->{message}; } elsif ($json->{access_token}) { return $self->{access_token} = $json->{access_token}; } else { croak "can't get long lived access token from " . $response->content(); } } sub debug_token { my ($self,%params) = @_; croak "You must pass the 'input' access token to inspect" unless defined $params{input}; # NOTE: according to FB's documentation, instead of passing an # app token we can simply pass access_token=app_id|app_secret: # https://developers.facebook.com/docs/facebook-login/access-tokens/#apptokens my $getURL = $self->{debug_token_url} . "?input_token=" . uri_escape($params{input}) . "&access_token=" . join('|', uri_escape($self->{options}->{application_id}), uri_escape($self->{options}->{application_secret}) ); my $response = $self->{browser}->get($getURL); my $json = decode_json($response->content()); if (!$response->is_success || exists $json->{error}){ ##got an error response from facebook. die and display error message croak "'" . $json->{error}->{type}. "'" . " " .$json->{error}->{message}; } elsif (!exists $json->{data}->{app_id} || !exists $json->{data}->{user_id}) { return; } elsif (!$params{skip_check} && (''.$json->{data}->{app_id}) ne (''.$self->{options}->{application_id}) ) { return; } return $json->{data}; } sub get { my ($self,$url,$params) = @_; unless ($self->_has_access_token($url)) { croak "You must pass access_token" unless defined $self->{access_token}; $url .= $self->{_has_query} ? '&' : '?'; $url .= "access_token=" . $self->{access_token}; } ##construct the new url my @array; while ( my ($key, $value) = each(%{$params})){ $value = uri_escape($value); push(@array, "$key=$value"); } my $string = join('&', @array); $url .= "&".$string if $string; my $response = $self->{browser}->get($url); my $content = $response->content(); return $self->_content($content); } sub post { my ($self,$url,$params) = @_; unless ($self->_has_access_token($url)) { croak "You must pass access_token" unless defined $self->{access_token}; $params->{access_token} = $self->{access_token}; } my $response = $self->{browser}->post($url,$params); my $content = $response->content(); return $self->_content($content); } sub delete { my ($self,$url,$params) = @_; unless ($self->_has_access_token($url)) { croak "You must pass access_token" unless defined $self->{access_token}; $params->{access_token} = $self->{access_token}; } my $response = $self->{browser}->delete($url,$params); my $content = $response->content(); return $self->_content($content); } sub as_hash { my ($self) = @_; return decode_json($self->{content}); } sub as_json { my ($self) = @_; return $self->{content}; } sub _content { my ($self,$content) = @_; $self->{content} = $content; return $self; } sub _has_access_token { my ($self, $url) = @_; my $uri = URI->new($url); my %q = $uri->query_form; #also check if we have a query and save result $self->{_has_query} = $uri->query(); if (grep { $_ eq 'access_token' } keys %q) { return 1; } return; } 1; __END__ =head1 NAME Net::Facebook::Oauth2 - a simple Perl wrapper around Facebook OAuth 2.0 protocol =for html =head1 FACEBOOK GRAPH API VERSION This module complies to Facebook Graph API version 4.0, the latest at the time of publication, B<< scheduled for deprecation not sooner than August 3rd, 2021 >>. =head1 SYNOPSIS Somewhere in your application's login process: use Net::Facebook::Oauth2; my $fb = Net::Facebook::Oauth2->new( application_id => 'your_application_id', application_secret => 'your_application_secret', callback => 'http://yourdomain.com/facebook/callback' ); # get the authorization URL for your application my $url = $fb->get_authorization_url( scope => [ 'email' ], display => 'page' ); Now redirect the user to this C<$url>. Once the user authorizes your application, Facebook will send him/her back to your application, on the C link provided above. PLEASE NOTE THAT YOU MUST PRE-AUTHORIZE YOUR CALLBACK URI ON FACEBOOK'S APP DASHBOARD. Inside that callback route, use the verifier code parameter that Facebook sends to get the access token: # param() below is a bogus function. Use whatever your web framework # provides (e.g. $c->req->param('code'), $cgi->param('code'), etc) my $code = param('code'); use Try::Tiny; # or eval {}, or whatever my ($unique_id, $access_token); try { $access_token = $fb->get_access_token(code => $code); # <-- could die! # Facebook tokens last ~2h, but you may upgrade them to ~60d if you want: $access_token = $fb->get_long_lived_token( access_token => $access_token ); my $access_data = $fb->debug_token( input => $access_token ); if ($access_data && $access_data->{is_valid}) { $unique_id = $access_data->{user_id}; # you could also check here for what scopes were granted to you # by inspecting $access_data->{scopes}->@* } } catch { # handle errors here! }; If you got so far, your user is logged! Save the access token in your database or session. As shown in the example above, Facebook also provides a unique I for this token so you can associate it with a particular user of your app. Later on you can use that access token to communicate with Facebook on behalf of this user: my $fb = Net::Facebook::Oauth2->new( access_token => $access_token ); my $info = $fb->get( 'https://graph.facebook.com/v4.0/me' # Facebook API URL ); print $info->as_json; NOTE: if you skipped the call to C you can still find the unique user id value with a call to the 'me' endpoint shown above, under C<< $info->{id} >> =head1 DESCRIPTION Net::Facebook::Oauth2 gives you a way to simply access FaceBook Oauth 2.0 protocol. The example folder contains some snippets you can look at, or for more information just keep reading :) =head1 SEE ALSO For more information about Facebook Oauth 2.0 API Please Check L get/post Facebook Graph API L =head1 USAGE =head2 Cnew( %args )> Returns a new object to handle user authentication. Pass arguments as a hash. The following arguments are I unless you're passing an access_token (see optional arguments below): =over 4 =item * C Your application id as you get from facebook developers platform when you register your application =item * C Your application secret id as you get from facebook developers platform when you register your application =back The following arguments are I: =over 4 =item * C If you want to instantiate an object to an existing access token, you may do so by passing it to this argument. =item * C The user agent that will handle requests to Facebook's API. Defaults to LWP::UserAgent, but can be any method that implements the methods C, C and C and whose response to such methods implements C and C. =item * C See C under the C method below. =item * C Use this to replace the API version on all endpoints. The default value is 'v4.0'. Note that defining an api_version parameter together with C, C or C is a fatal error. =item * C Overrides the default (4.0) API endpoint for Facebook's oauth. Used mostly for testing new versions. =item * C Overrides the default (4.0) API endpoint for Facebook's access token. Used mostly for testing new versions. =item * C Overrides the default (4.0) API endpoint for Facebook's token information. Used mostly for testing new versions. =back =head2 C<$fb-Eget_authorization_url( %args )> Returns an authorization URL for your application. Once you receive this URL, redirect your user there in order to authorize your application. The following argument is I: =over 4 =item * C callback => 'http://example.com/login/facebook/success' The callback URL, where Facebook will send users after they authorize your application. YOU MUST CONFIRM THIS URL ON FACEBOOK'S APP DASHBOARD. To do that, go to the App Dashboard, click Facebook Login in the right-hand menu, and check the B in the Client OAuth Settings section. =back This method also accepts the following I arguments: =over 4 =item * C scope => ['user_birthday','user_friends', ...] Array of Extended permissions as described by the Facebook Oauth API. You can get more information about scope/Extended Permission from L Please note that requesting information other than C, C and C B =item * C state => '123456abcde' An arbitrary unique string provided by you to guard against Cross-site Request Forgery. This value will be returned to you by Facebook, unchanged. Note that, as of Facebook API v3.0, this argument is I, so if you don't provide a 'state' argument, we will default to C. =item * C When a user declines a given permission, you must reauthorize them. But when you do so, any previously declined permissions will not be asked again by Facebook. Set this argument to C<'rerequest'> to explicitly tell the dialog you're re-asking for a declined permission. =item * C display => 'page' How to display Facebook Authorization page. Defaults to C. Can be any of the following: =over 4 =item * C This will display facebook authorization page as full page =item * C This option is useful if you want to popup authorization page as this option tell facebook to reduce the size of the authorization page =item * C From the name, for wab and mobile applications this option is the best, as the facebook authorization page will fit there :) =back =item * C response_type => 'code' When the redirect back to the app occurs, determines whether the response data is in URL parameters or fragments. Defaults to C, which is Facebook's default and useful for cases where the server handles the token (which is most likely why you are using this module), but can be also be C, C, or C. Note that changing this to anything other than 'code' might change the login flow described in this documentation, rendering calls to C pointless. Please see L<< Facebook's login documentation|https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow >> for more information. =back =head2 C<$fb-Eget_access_token( %args )> This method issues a GET request to Facebook's API to retrieve the access token string for the specified code (passed as an argument). Returns the access token string or raises an exception in case of errors (B). Note that Facebook's access tokens are short-lived, around 2h of idle time before expiring. If you want to "upgrade" the token to a long lived one (with around 60 days of idle time), use this token to feed the C method. You should call this method inside the route for the callback URI defined in the C method. It receives the following arguments: =over 4 =item * C This is the verifier code that Facebook sends back to your callback URL once user authorize your app, you need to capture this code and pass to this method in order to get the access token. Verifier code will be presented with your callback URL as code parameter as the following: http://your-call-back-url.com?code=234er7y6fdgjdssgfsd... Note that if you have fiddled with the C argument, you might not get this parameter properly. =back When the access token is returned you need to save it in a secure place in order to use it later in your application. The token indicates that a user has authorized your site/app, meaning you can associate that token to that user and issue API requests to Facebook on their behalf. To know I user has granted you the authorization (e.g. when building a login system to associate that token with a unique user on your database), you must make a request to fetch Facebook's own unique identifier for that user, and then associate your own user's unique id to Facebook's. This was usually done by making a GET request to the C API endpoint and looking for the 'id' field. However, Facebook has introduced a new endpoint for that flow that returns the id (this time as 'user_id') and some extra validation data, like whether the token is valid, to which app it refers to, what scopes the user agreed to, etc, so now you are encouraged to call the C method as shown in the SYNOPSIS. B Expect that the length of all access token types will change over time as Facebook makes changes to what is stored in them and how they are encoded. You can expect that they will grow and shrink over time. Please use a variable length data type without a specific maximum size to store access tokens. =head2 C<$fb-Eget_long_lived_token( access_token =E $access_token )> Asks facebook to retrieve the long-lived (~60d) version of the provided short-lived (~2h) access token retrieved from C. If successful, this method will return the long-lived token, which you can use to replace the short-lived one. Otherwise, it croaks with an error message, in which case you can continue to use the short-lived version. L for the gory details. =head2 C<$fb-Edebug_token( input =E $access_token )> This method should be called right after C. It will query Facebook for details about the given access token and validate that it was indeed granted to your app (and not someone else's). It requires a single argument, C, containing the access code obtained from calling C. It croaks on HTTP/connection/Facebook errors, returns nothing if for whatever reason the response is invalid without errors (e.g. no app_id and no user_id), and also if the returned app_id is not the same as your own application_id (pass a true value to C to skip this validation). If all goes well, it returns a hashref with the JSON structure returned by Facebook. =head2 C<$fb-Eget( $url, $args )> Sends a GET request to Facebook and stores the response in the given object. =over 4 =item * C Facebook Graph API URL as string. You must provide the full URL. =item * C<$args> hashref of parameters to be sent with graph API URL if required. =back You can access the response using the following methods: =over 4 =item * C<$responseEas_json> Returns response as json object =item * C<$responseEas_hash> Returns response as perl hashref =back For more information about facebook graph API, please check http://developers.facebook.com/docs/api =head2 C<$fb-Epost( $url, $args )> Send a POST request to Facebook and stores the response in the given object. See the C and C methods above for how to retrieve the response. =over 4 =item * C Facebook Graph API URL as string =item * C<$args> hashref of parameters to be sent with graph API URL =back For more information about facebook graph API, please check L =head2 C<$fb-Edelete( $url, $args )> Send a DELETE request to Facebook and stores the response in the given object. See the C and C methods above for how to retrieve the response. =over 4 =item * C Facebook Graph API URL as string =item * C<$args> hashref of parameters to be sent with graph API URL =back =head1 AUTHOR Mahmoud A. Mehyar, Emamod.mehyar@gmail.comE =head1 CONTRIBUTORS Big Thanks To =over 4 =item * Takatsugu Shigeta L<@comewalk|https://github.com/comewalk> =item * Breno G. de Oliveira L<@garu|https://github.com/garu> =item * squinker L<@squinker|https://github.com/squinker> =item * Valcho Nedelchev L<@valchonedelchev|https://github.com/valchonedelchev> =back =head1 COPYRIGHT AND LICENSE Copyright (C) 2012-2019 by Mahmoud A. Mehyar This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.1 or, at your option, any later version of Perl 5 you may have available. =cut Net-Facebook-Oauth2-0.12/Makefile.PL0000644000175000017500000000253613615636414015776 0ustar mamodmamoduse ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( NAME => 'Net::Facebook::Oauth2', VERSION_FROM => 'lib/Net/Facebook/Oauth2.pm', # finds $VERSION PREREQ_PM => { 'LWP::UserAgent' => 0, 'LWP::Protocol::https' => 0, 'URI' => 0, 'Carp' => 0, 'URI::Escape' => 0, 'JSON::MaybeXS' => 0, }, BUILD_REQUIRES => { 'Test::More' => 0.88, 'Test::Exception' => 0, 'Test::MockObject' => 0, 'Test::MockModule' => 0, 'Plack::Request' => 0, 'Plack::Loader' => 0, 'Test::Requires' => 0, 'Test::TCP' => 0, }, ($] >= 5.005 ? ## Add these new keywords supported since 5.005 ( ABSTRACT_FROM => 'lib/Net/Facebook/Oauth2.pm', # retrieve abstract from module AUTHOR => 'Mahmoud A. Mehyar ' ) : () ), META_MERGE => { resources => { license => 'http://dev.perl.org/licenses/', bugtracker => 'https://github.com/mamod/Net-Facebook-Oauth2/issues', repository => 'https://github.com/mamod/Net-Facebook-Oauth2', }, }, ); Net-Facebook-Oauth2-0.12/MANIFEST0000644000175000017500000000053013615640370015141 0ustar mamodmamodChanges examples/Catalyst/Facebook.pm examples/CGI/facebook.pl lib/Net/Facebook/Oauth2.pm Makefile.PL MANIFEST MANIFEST.SKIP README.pod t/accesstoken.t t/Net-Facebook-Oauth2.t META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) Net-Facebook-Oauth2-0.12/Changes0000644000175000017500000000256113615640012015302 0ustar mamodmamodRevision history for Perl module Net::Facebook::Oauth2. 0.12 - update to Graph API v4.0 0.11 - update to Graph API v3.1 - allow custom API version setting (GH#15) - new method debug_token() to fetch access token metadata from Facebook - new method get_long_lived_token() to upgrade access tokens - add missing dep - documentation updates 0.10 2016 2016-10-14 - Update to Graph API v2.8 - add missing deps - minor code tidying - documentation improvements - trigger warning when API is about to deprecate - update example and readme to v2.8 - All changes in this release contributed by (Breno G. de Oliveira) 0.09 2015 2015-03-25 - Code clean (Breno G. de Oliveira) - Using JSON::MaybeXS instead of deprecated JSON::ANY (Breno G. de Oliveira) - Update Facebook graph API to version 2.2 (Breno G. de Oliveira) 0.08 2013 2013-10-10 - Bug fix reported by Emad Fanous, adding query to already existing one - Update Changes File 0.07 2013 2013-08-21 - Updating MANIFEST file to include examples folder 0.06 2013-05-28 - Allow Browser options to pass in by & tests (William Bellamy) - Changed behavior to access_token & tests by (Takatsugu Shigeta) 0.03 2012 2012-09-01 - Fixed some bugs - Fixed documentations and examples - Added more examples 0.02 2010-07-29 - Fixed some methods - Added better documentations - Added more examples Net-Facebook-Oauth2-0.12/META.json0000664000175000017500000000313313615640370015435 0ustar mamodmamod{ "abstract" : "a simple Perl wrapper around Facebook OAuth 2.0 protocol", "author" : [ "Mahmoud A. Mehyar " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.0401, CPAN::Meta::Converter version 2.150001", "license" : [ "unknown" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Net-Facebook-Oauth2", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "Plack::Loader" : "0", "Plack::Request" : "0", "Test::Exception" : "0", "Test::MockModule" : "0", "Test::MockObject" : "0", "Test::More" : "0.88", "Test::Requires" : "0", "Test::TCP" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Carp" : "0", "JSON::MaybeXS" : "0", "LWP::Protocol::https" : "0", "LWP::UserAgent" : "0", "URI" : "0", "URI::Escape" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/mamod/Net-Facebook-Oauth2/issues" }, "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "url" : "https://github.com/mamod/Net-Facebook-Oauth2" } }, "version" : "0.12" } Net-Facebook-Oauth2-0.12/README.pod0000644000175000017500000000707113615640012015451 0ustar mamodmamod=head1 NAME Net::Facebook::Oauth2 - a simple Perl wrapper around Facebook OAuth 2.0 protocol =for html =head1 SYNOPSIS Somewhere in your application's login process: use Net::Facebook::Oauth2; my $fb = Net::Facebook::Oauth2->new( application_id => 'your_application_id', application_secret => 'your_application_secret', callback => 'http://yourdomain.com/facebook/callback' ); # get the authorization URL for your application my $url = $fb->get_authorization_url( scope => [ 'name', 'email', 'profile_picture' ], display => 'page' ); Now redirect the user to this C<$url>. Once the user authorizes your application, Facebook will send him/her back to your application, on the C link provided above. PLEASE NOTE THAT YOU MUST PRE-AUTHORIZE YOUR CALLBACK URI ON FACEBOOK'S APP DASHBOARD. Inside that callback route, use the verifier code parameter that Facebook sends to get the access token: # param() below is a bogus function. Use whatever your web framework # provides (e.g. $c->req->param('code'), $cgi->param('code'), etc) my $code = param('code'); use Try::Tiny; # or eval {}, or whatever my ($unique_id, $access_token); try { $access_token = $fb->get_access_token(code => $code); # <-- could die! # Facebook tokens last ~2h, but you may upgrade them to ~60d if you want: $access_token = $fb->get_long_lived_token( access_token => $access_token ); my $access_data = $fb->debug_token( input => $access_token ); if ($access_data && $access_data->{is_valid}) { $unique_id = $access_data->{user_id}; # you could also check here for what scopes were granted to you # by inspecting $access_data->{scopes}->@* } } catch { # handle errors here! }; If you got so far, your user is logged! Save this access token in your database or session. As shown in the example above, Facebook also provides a unique I for this token so you can associate it with a particular user of your app. Later on you can use it to communicate with Facebook on behalf of this user: my $fb = Net::Facebook::Oauth2->new( access_token => $access_token ); my $info = $fb->get( 'https://graph.facebook.com/v4.0/me' # Facebook API URL ); print $info->as_json; =head1 DESCRIPTION Net::Facebook::Oauth2 gives you a way to simply access FaceBook Oauth 2.0 protocol For more information please see example folder shipped with this Module, or refer to the L. =head1 INSTALLATION cpanm Net::Facebook::Oauth2 Or the old-fashioned manual way: perl Makefile.PL make make test make install =head1 AUTHOR Mahmoud A. Mehyar, Emamod.mehyar@gmail.comE =head1 CONTRIBUTORS Big Thanks To =over 4 =item * Takatsugu Shigeta L<@comewalk|https://github.com/comewalk> =item * Breno G. de Oliveira L<@garu|https://github.com/garu> =item * squinker L<@squinker|https://github.com/squinker> =item * Valcho Nedelchev L<@valchonedelchev|https://github.com/valchonedelchev> =back =head1 COPYRIGHT AND LICENSE Copyright (C) 2012-2019 by Mahmoud A. Mehyar This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.1 or, at your option, any later version of Perl 5 you may have available. =cut Net-Facebook-Oauth2-0.12/t/0000755000175000017500000000000013615640370014255 5ustar mamodmamodNet-Facebook-Oauth2-0.12/t/Net-Facebook-Oauth2.t0000644000175000017500000000740513615636414020051 0ustar mamodmamoduse warnings; use strict; use Net::Facebook::Oauth2; use Test::More; ######################### ######################### # Fixture Data my $app_id = 'testapp_id'; my $app_secret = 'test_app_secret'; my $access_token = 'test_access_token'; my $url = 'test.www.com'; my $class = 'Net::Facebook::Oauth2'; eval "use Test::Requires qw/Test::Exception Test::MockObject Test::MockModule/"; if ($@){ plan skip_all => 'Test::Requires required for testing'; } else { #had to re use??! use Test::Exception; use Test::MockObject; use Test::MockModule; can_instantiate_class(); test_get_method_with_no_browser_parameter(); can_pass_browser_param(); can_do_delete_request(); done_testing(); } sub can_instantiate_class { my $net_fb_oauth2 = $class->new( application_id => $app_id, application_secret => $app_secret, ); ok $net_fb_oauth2, "Can instantiate $class with application_id and application_secret"; dies_ok { $class->new( application_id => $app_id ) } 'Dies if no application_secret passed to constructor'; dies_ok { $class->new( application_secret => $app_secret ) } 'Dies if no application_id passed to constructor'; } sub test_get_method_with_no_browser_parameter { # Test that browser attribute is LWP::UserAgent if no browser param passed my $test_json = '{"data":"this is the get data"}'; my $mock_get_response = _mock_object( { is_success => 1, content => $test_json, } ); # Mock LWP::UserAgent methods so can test offline my $mock_user_agent = _mock_object( { get => $mock_get_response, } ); my $mock_user_agent_module = new Test::MockModule('LWP::UserAgent'); $mock_user_agent_module->mock( 'new', sub {return $mock_user_agent;} ); my $net_fb_oauth2 = $class->new( application_id => $app_id, application_secret => $app_secret, access_token => $access_token, ); is $net_fb_oauth2->get( $url )->as_json, $test_json, 'Passing no browser param will use LWP::UserAgent'; } sub can_pass_browser_param { my $test_json = '{"data":"this is the get data"}'; my $mock_get_response = _mock_object( { is_success => 1, content => $test_json, } ); my $mock_browser = _mock_object( { get => $mock_get_response, } ); my $net_fb_oauth2 = $class->new( application_id => $app_id, application_secret => $app_secret, access_token => $access_token, browser => $mock_browser, ); is $net_fb_oauth2->get( $url )->as_json, $test_json, 'Can pass browser param'; } sub can_do_delete_request { my $test_json = '{"data":"this is the delete data"}'; my $mock_delete_response = _mock_object( { is_success => 1, content => $test_json, } ); # Mock LWP::UserAgent methods so can test offline my $mock_user_agent = _mock_object( { delete => $mock_delete_response, } ); my $mock_user_agent_module = new Test::MockModule('LWP::UserAgent'); $mock_user_agent_module->mock( 'new', sub {return $mock_user_agent;} ); my $net_fb_oauth2 = $class->new( application_id => $app_id, application_secret => $app_secret, access_token => $access_token, ); is $net_fb_oauth2->delete( $url )->as_json, $test_json, 'Delete request returns correct JSON'; } sub _mock_object { my $mock_kv = shift; my $mock_object = Test::MockObject->new; while ( my($key, $value) = each %$mock_kv) { $mock_object->set_always($key, $value); } return $mock_object; } Net-Facebook-Oauth2-0.12/t/accesstoken.t0000644000175000017500000000466113615636414016757 0ustar mamodmamoduse strict; use warnings; use Test::More; use Net::Facebook::Oauth2; eval "use Test::Requires qw/Plack::Loader Test::TCP Plack::Request/"; plan skip_all => 'Test::Requires required for testing with Test::TCP' if $@; my $app = sub { my $env = shift; my $req = Plack::Request->new($env); my $access_token = $req->param('access_token'); my $message = $req->param('message'); if ($message =~ m/without access token/) { is $access_token, 'AccessToken', $message; } elsif ($message =~ m/with access token/) { is $access_token, 'OtherToken', $message; } elsif ($message =~ m/with already set query/) { my $query = $env->{QUERY_STRING}; ok($query !~ /limit=1000\?/); ok($query =~ /^limit=1000&access_token/); } elsif ($message =~ m/without already set query/) { my $query = $env->{QUERY_STRING}; ok($query =~ /^access_token/); } elsif ($message =~ m/Get request with token and query/) { my $query = $env->{QUERY_STRING}; ok($query =~ /^limit=1000&access_token=OtherToken&message/); } return [ 200, [ 'Content-Type' => 'text/plain' ], [ 'OK' ] ]; }; test_tcp( client => sub { my $port = shift; my $fb = Net::Facebook::Oauth2->new( application_id => 'your_application_id', application_secret => 'your_application_secret', callback => 'http://your-domain.com/callback', access_token => 'AccessToken', ); my $url = "http://127.0.0.1:$port"; $fb->post($url, { message => 'Post request without access token' }); $fb->post("$url?access_token=OtherToken", { message => 'Post request with access token' }); $fb->get($url, { message => 'Get request without access token' }); $fb->get("$url?access_token=OtherToken", { message => 'Get request with access token' }); ##new bug tests -- adding query to another query ?limit=100?access_token $fb->get("$url?limit=1000", { message => 'Get request with already set query' }); $fb->get("$url", { message => 'Get request without already set query' }); $fb->get("$url?limit=1000&access_token=OtherToken", { message => 'Get request with token and query' }); }, server => sub { my $port = shift; my $server = Plack::Loader->auto( port => $port, host => '127.0.0.1', ); $server->run($app); }, ); done_testing(8); __END__