File Coverage

blib/lib/Lemonldap/NG/Portal/AuthFacebook.pm
Criterion Covered Total %
statement 4 6 66.6
branch n/a
condition n/a
subroutine 2 2 100.0
pod n/a
total 6 8 75.0


line stmt bran cond sub pod time code
1             ##@file
2             # Facebook authentication backend file
3              
4             ##@class
5             # Facebook authentication backend class.
6             #
7             # You need to have an application ID and an application secret (take a look at
8             # https://developers.facebook.com/apps
9             package Lemonldap::NG::Portal::AuthFacebook;
10              
11 1     1   504 use strict;
  1         1  
  1         30  
12 1     1   570 use Lemonldap::NG::Portal::Simple;
  0            
  0            
13             use Lemonldap::NG::Common::Regexp;
14             use Lemonldap::NG::Portal::_Browser;
15             use URI::Escape;
16              
17             our @ISA = (qw(Lemonldap::NG::Portal::_Browser));
18             our $VERSION = '1.4.0';
19             our $initDone;
20              
21             BEGIN {
22             eval {
23             require threads::shared;
24             threads::shared::share($initDone);
25             };
26             }
27              
28             ## @method Net::Facebook::Oauth2 fb()
29             # @return Net::Facebook::Oauth2 object
30             sub fb {
31             my $self = shift;
32             return $self->{_fb} if ( $self->{_fb} );
33              
34             # Build callback uri
35             my $sep = '?';
36             my $ret = $self->{portal};
37             foreach my $v (
38             [ $self->{_url}, "url" ],
39             [ $self->param( $self->{authChoiceParam} ), $self->{authChoiceParam} ]
40             )
41             {
42             if ( $v->[0] ) {
43             $ret .= "$sep$v->[1]=$v->[0]";
44             $sep = '&';
45             }
46             }
47              
48             # Build Net::Facebook::Oauth2 object
49             eval {
50             $self->{_fb} = Net::Facebook::Oauth2->new(
51             application_id => $self->{facebookAppId},
52             application_secret => $self->{facebookAppSecret},
53             callback => $ret,
54             );
55             };
56             unless ( $self->{_fb} ) {
57             $self->abort( 'Unable to build Net::Facebook::Oauth2 object', $@ );
58             }
59             return $self->{_fb};
60             }
61              
62             ## @apmethod int authInit()
63             # @return Lemonldap::NG::Portal constant
64             sub authInit {
65             my $self = shift;
66             unless ($initDone) {
67             eval { require Net::Facebook::Oauth2; };
68             $self->abort( 'Unable to load Net::Facebook::Oauth2', $@ ) if ($@);
69             foreach my $arg (qw(facebookAppId facebookAppSecret)) {
70             $self->abort("Parameter $arg is required") unless ( $self->{$arg} );
71             }
72             $initDone++;
73             }
74             PE_OK;
75             }
76              
77             ## @apmethod int extractFormInfo()
78             # Read username return by Facebook authentication system.
79             # @return Lemonldap::NG::Portal constant
80             sub extractFormInfo {
81             my $self = shift;
82              
83             # 1. Check Facebook responses
84              
85             # 1.1 Good responses
86             if ( my $code = $self->param('code') ) {
87             if ( my $access_token = $self->fb()->get_access_token( code => $code ) )
88             {
89             $self->{sessionInfo}->{_facebookToken} = $access_token;
90              
91             # Get fields (see https://developers.facebook.com/tools/explorer)
92             my @fields = ( 'id', 'username' );
93              
94             # Look at wanted fields
95             my %vars =
96             ( %{ $self->{exportedVars} },
97             %{ $self->{facebookExportedVars} } );
98             if ( $self->get_module('user') =~ /^Facebook/ ) {
99             push @fields, map { /^(\w+)$/ ? ($1) : () } values %vars;
100             }
101             my $datas;
102              
103             # When a field is not granted, Facebook returns only an error
104             # without real explanation. So here we try to reduce query until
105             # having a valid response
106             while (@fields) {
107             $datas = $self->fb->get(
108             'https://graph.facebook.com/me',
109             { fields => join( ',', @fields ) }
110             )->as_hash;
111             unless ( ref $datas ) {
112             $self->lmLog( "Unable to get any Facebook field", 'error' );
113             return PE_ERROR;
114             }
115             if ( $datas->{error} ) {
116             my $tmp = pop @fields;
117             $self->lmLog(
118             "Unable to get some Facebook fields ($datas->{error}->{message}). Retrying without $tmp",
119             'warn'
120             );
121             }
122             else {
123             last;
124             }
125             }
126             unless (@fields) {
127             $self->lmLog( "Unable to get any Facebook field", 'error' );
128             return PE_ERROR;
129             }
130              
131             # Look if a field can be used to trace user
132             unless ( $self->{user} = $datas->{username} ) {
133             $self->lmLog( 'Unable to get Facebook username', 'warn' );
134             unless ( $self->{user} = $datas->{id} ) {
135             $self->lmLog( 'Unable to get Facebook id', 'error' );
136             return PE_ERROR;
137             }
138             }
139             $self->{_facebookDatas} = $datas;
140              
141             # Force redirection to avoid displaying Oauth datas
142             $self->{mustRedirect} = 1;
143             return PE_OK;
144             }
145             return PE_BADCREDENTIALS;
146             }
147              
148             # 1.2 Bad responses
149             if ( my $error_code = $self->param('error_code') ) {
150             my $error_message = $self->param('error_message');
151             $self->lmLog( "Facebook error code $error_code: $error_message",
152             'error' );
153             return PE_ERROR;
154             }
155              
156             # 2. Else redirect user to Facebook login page:
157              
158             # Build Facebook redirection
159             # TODO: use a param to use "publish_stream" or not
160             my $check_url = $self->fb()->get_authorization_url(
161             scope => ['offline_access'],
162             display => 'page',
163             );
164             print $self->redirect($check_url);
165             $self->quit();
166             }
167              
168             ## @apmethod int setAuthSessionInfo()
169             # Set _user and authenticationLevel.
170             # @return Lemonldap::NG::Portal constant
171             sub setAuthSessionInfo {
172             my $self = shift;
173              
174             $self->{sessionInfo}->{'_user'} = $self->{user};
175              
176             $self->{sessionInfo}->{authenticationLevel} = $self->{facebookAuthnLevel}
177             || 1;
178              
179             PE_OK;
180             }
181              
182             ## @apmethod int authenticate()
183             # Does nothing.
184             # @return Lemonldap::NG::Portal constant
185             sub authenticate {
186             PE_OK;
187             }
188              
189             ## @apmethod int authFinish()
190             # Does nothing.
191             # @return Lemonldap::NG::Portal constant
192             sub authFinish {
193             PE_OK;
194             }
195              
196             ## @apmethod int authLogout()
197             # Does nothing
198             # @return Lemonldap::NG::Portal constant
199             sub authLogout {
200             PE_OK;
201             }
202              
203             ## @apmethod boolean authForce()
204             # Does nothing
205             # @return result
206             sub authForce {
207             return 0;
208             }
209              
210             ## @method string getDisplayType
211             # @return display type
212             sub getDisplayType {
213             return "logo";
214             }
215              
216             1;
217             __END__
218              
219             =head1 NAME
220              
221             =encoding utf8
222              
223             Lemonldap::NG::Portal::AuthFacebook - Perl extension for building Lemonldap::NG
224             compatible portals with Facebook authentication.
225              
226             =head1 SYNOPSIS
227              
228             use Lemonldap::NG::Portal::SharedConf;
229             my $portal = new Lemonldap::NG::Portal::Simple(
230             configStorage => {...}, # See Lemonldap::NG::Portal
231             authentication => 'Facebook',
232             );
233              
234             if($portal->process()) {
235             # Write here the menu with CGI methods. This page is displayed ONLY IF
236             # the user was not redirected here.
237             print $portal->header('text/html; charset=utf-8'); # DON'T FORGET THIS (see CGI(3))
238             print "...";
239             }
240             else {
241             # If the user enters here, IT MEANS THAT CAS REDIRECTION DOES NOT WORK
242             print $portal->header('text/html; charset=utf-8'); # DON'T FORGET THIS (see CGI(3))
243             print "<html><body><h1>Unable to work</h1>";
244             print "This server isn't well configured. Contact your administrator.";
245             print "</body></html>";
246             }
247              
248             =head1 DESCRIPTION
249              
250             This library just overload few methods of Lemonldap::NG::Portal::Simple to use
251             Facebook authentication mechanism.
252              
253             See L<Lemonldap::NG::Portal::Simple> for usage and other methods.
254              
255             =head1 SEE ALSO
256              
257             L<Lemonldap::NG::Portal>, L<Lemonldap::NG::Portal::Simple>,
258             L<http://lemonldap-ng.org/>, L<Net::Facebook::Oauth2>
259             L<https://developers.facebook.com/docs/>
260              
261             =head1 AUTHOR
262              
263             =over
264              
265             =item Xavier Guimard, E<lt>x.guimard@free.frE<gt>
266              
267             =back
268              
269             =head1 BUG REPORT
270              
271             Use OW2 system to report bug or ask for features:
272             L<http://jira.ow2.org>
273              
274             =head1 DOWNLOAD
275              
276             Lemonldap::NG is available at
277             L<http://forge.objectweb.org/project/showfiles.php?group_id=274>
278              
279             =head1 COPYRIGHT AND LICENSE
280              
281             =over
282              
283             =item Copyright (C) 2013 by Xavier Guimard, E<lt>x.guimard@free.frE<gt>
284              
285             =back
286              
287             This library is free software; you can redistribute it and/or modify
288             it under the terms of the GNU General Public License as published by
289             the Free Software Foundation; either version 2, or (at your option)
290             any later version.
291              
292             This program is distributed in the hope that it will be useful,
293             but WITHOUT ANY WARRANTY; without even the implied warranty of
294             MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
295             GNU General Public License for more details.
296              
297             You should have received a copy of the GNU General Public License
298             along with this program. If not, see L<http://www.gnu.org/licenses/>.
299              
300             =cut
301