File Coverage

blib/lib/Lemonldap/NG/Portal/AuthGoogle.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             # Google authentication backend file
3              
4             ##@class
5             # Google authentication backend class.
6             package Lemonldap::NG::Portal::AuthGoogle;
7              
8 1     1   508 use strict;
  1         1  
  1         32  
9 1     1   657 use Lemonldap::NG::Portal::Simple;
  0            
  0            
10             use Lemonldap::NG::Common::Regexp;
11             use Lemonldap::NG::Portal::_Browser;
12             use URI::Escape;
13              
14             use constant AXSPECURL => 'http://openid.net/srv/ax/1.0';
15             use constant GOOGLEENDPOINT => 'https://www.google.com/accounts/o8/id';
16              
17             our @ISA = (qw(Lemonldap::NG::Portal::_Browser));
18             our $VERSION = '1.4.0';
19             our $googleEndPoint;
20              
21             BEGIN {
22             eval {
23             require threads::shared;
24             threads::shared::share($googleEndPoint);
25             };
26             }
27              
28             ## @method string googleEndPoint()
29             # Return the Google OpenID endpoint given by
30             # https://www.google.com/accounts/o8/id
31             # @return string
32             sub googleEndPoint {
33             my $self = shift;
34              
35             # First time, get and store Google endpoint
36             unless ($googleEndPoint) {
37             my $response =
38             $self->ua()->get( GOOGLEENDPOINT, Accept => 'application/xrds+xml' );
39             if ( $response->is_success ) {
40              
41             # Dirty XML parse
42             # (searching for <URI>https://www.google.com/accounts/o8/ud</URI>)
43             my $tmp = $response->decoded_content;
44             if ( $tmp =~ m#<URI.*?>\s*(\S+)\s*</URI>#mi ) {
45             $googleEndPoint = $1;
46             }
47             else {
48             $self->lmLog(
49             'Here is the Google response: '
50             . $response->decoded_content,
51             'error'
52             );
53             $self->abort('Can\'t find endpoint in Google response');
54             }
55             }
56             else {
57             $self->abort( 'Can\'t access to Google endpoint:',
58             $response->status_line );
59             }
60             }
61             return $googleEndPoint;
62             }
63              
64             ## @method boolean checkGoogleSession()
65             # Search for claimed_id in persistent sessions DB.
66             # @return true if sessions was recovered
67             sub checkGoogleSession {
68             my $self = shift;
69              
70             # Find in Google response for AX attributes
71             # See https://developers.google.com/accounts/docs/OpenID#Parameters
72             # for more
73             ( $self->{_AXNS} ) = map {
74             ( /^openid\.ns\.(.*)/ and $self->param($_) eq AXSPECURL )
75             ? ($1)
76             : ()
77             } $self->param();
78              
79             # Look at persistent database
80             my $id = $self->_md5hash( $self->param('openid.claimed_id') );
81             my $pSession = $self->getPersistentSession($id);
82             my $gs;
83              
84             # No AX response, if datas are already shared, store them
85             unless ( $self->{_AXNS} ) {
86             if ( $pSession->data ) {
87             $self->{user} = $pSession->data->{email};
88             while ( my ( $k, $v ) = each %{ $pSession->data } ) {
89             $gs->{$k} = $v;
90             }
91             }
92             }
93             else { # Parse AX response
94              
95             # First store email as user key. Note that this is the returned value
96             # so if it's empty, request is retried
97             $self->{user} = $self->param("openid.$self->{_AXNS}.value.email");
98              
99             # Retrieve AX datas (and store them in persistent session)
100             my $infos;
101             foreach my $k ( $self->param() ) {
102             if ( $k =~ /^openid\.$self->{_AXNS}\.value\.(\w+)$/ ) {
103             $gs->{$1} = $infos->{$1} = $self->param($k);
104             }
105             }
106             $pSession->update($infos);
107             }
108              
109             # Now store datas in session
110             my %vars = ( %{ $self->{exportedVars} }, %{ $self->{googleExportedVars} } );
111             while ( my ( $k, $v ) = each %vars ) {
112             my $attr = $k;
113             $attr =~ s/^!//;
114              
115             # Value (ie AX attribute) must be one of:
116             if ( $v =~ Lemonldap::NG::Common::Regexp::GOOGLEAXATTR() ) {
117              
118             # One value is missing:
119             unless ( exists( $gs->{$v} ) ) {
120              
121             # Case 1: value was asked but not returned, set an empty value
122             # in persistent session (so that it's defined)
123             if ( $self->{_AXNS} ) {
124             $self->_sub( 'userInfo',
125             "$v required attribute is missing in Google response, storing ''"
126             );
127             $gs->{$v} = '';
128             $pSession->update( { $v => '' } );
129             }
130              
131             # Case 2: value is not stored, probably configuration has
132             # changed and this value was never asked
133             else {
134             $self->_sub( 'userInfo',
135             "$v required attribute is missing in persistent session, let's ask it"
136             );
137             return 0;
138             }
139             }
140             $self->{sessionInfo}->{$attr} = $gs->{$v};
141             }
142              
143             # If an exported variable is not AX compliant, just warn
144             else {
145             $self->lmLog(
146             "Ignoring attribute $v which is not a valid Google OpenID AX attribute",
147             'warn'
148             );
149             }
150             }
151              
152             # Boolean value: ~false if no $user value
153             return $self->{user};
154             }
155              
156             ## @apmethod int authInit()
157             # @return Lemonldap::NG::Portal constant
158             sub authInit {
159             PE_OK;
160             }
161              
162             ## @apmethod int extractFormInfo()
163             # Read username return by Google authentication system.
164             # @return Lemonldap::NG::Portal constant
165             sub extractFormInfo {
166             my $self = shift;
167             my $ax = '';
168              
169             # 1. Check Google responses
170             if ( $self->param('openid.mode') ) {
171              
172             # 1.1 First, verify that the response isn't forged
173              
174             # Build verification request
175             my $check_url = $self->googleEndPoint() . "?" . join(
176             '&',
177             map {
178             my $val = $self->param($_);
179             $val = 'check_authentication' if $_ eq 'openid.mode';
180             sprintf '%s=%s', uri_escape_utf8($_), uri_escape_utf8($val);
181             } $self->param()
182             );
183              
184             # Launch request
185             my $response = $self->ua()->get( $check_url, Accept => 'text/plain' );
186             unless ( $response->is_success ) {
187             $self->abort( 'Can\'t verify Google authentication',
188             $response->status_line );
189             }
190             else {
191             my %tmp =
192             map { my ( $key, $value ) = split /:/, $_, 2; $key => $value }
193             split /\n/, $response->decoded_content;
194              
195             # Reject invalid requests
196             unless ( $tmp{is_valid} eq 'true' ) {
197             return PE_BADCREDENTIALS;
198             }
199              
200             # 1.2 Check if datas are already shared with Google
201             unless ( $self->checkGoogleSession() ) {
202              
203             # Datas are missing, prepare AX query which will be added to
204             # the request to Google
205              
206             # a) email is required, will be used as 'user' field
207             $ax =
208             '&openid.ns.ax='
209             . AXSPECURL
210             . '&openid.ax.mode=fetch_request'
211             . '&openid.ax.type.email=http://axschema.org/contact/email'
212             . '&openid.ax.required=email';
213              
214             # b) if UserDB is Google, ask for exported variables
215             if ( $self->get_module('user') eq 'Google' ) {
216             my $u;
217             while ( my ( $v, $k ) = each %{ $self->{exportedVars} } ) {
218             next if ( $k eq 'email' );
219              
220             # Check if wanted attribute is known by Google
221             if ( $k =~
222             /^(?:(?:la(?:nguag|stnam)|firstnam)e|country)$/ )
223             {
224             $ax .= ",$k";
225              
226             # Note: AX type seems to be required by Google
227             $u .= "&openid.ax.type.$k="
228             . {
229             country =>
230             "http://axschema.org/contact/country/home",
231             firstname =>
232             "http://axschema.org/namePerson/first",
233             lastname =>
234             "http://axschema.org/namePerson/last",
235             language => "http://axschema.org/pref/language"
236             }->{$k};
237             }
238             else {
239             $self->lmLog(
240             "Field name: $k is not exported by Google",
241             'warn' );
242             }
243             }
244             $ax .= $u;
245             }
246             }
247              
248             # 1.3 Datas are recovered, user is authenticated
249             else {
250             $self->lmLog( 'Good Google authentication', 'debug' );
251              
252             # Force redirection to avoid displaying OpenID datas
253             $self->{mustRedirect} = 1;
254             return PE_OK;
255             }
256             }
257             }
258              
259             # 2. Redirect user to Google login page:
260             # => no OpenID response or missing datas
261              
262             # Build request to Google
263             my $check_url =
264             $self->googleEndPoint()
265             . '?openid.mode=checkid_setup'
266             . '&openid.ns=http://specs.openid.net/auth/2.0'
267             . '&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select'
268             . '&openid.identity=http://specs.openid.net/auth/2.0/identifier_select'
269             . $ax; # Requested attributes if set
270              
271             # Build portal URI...
272             my $sep = '?';
273             my $returnTo = $self->{portal};
274             foreach my $v (
275             [ $self->{_url}, "url" ],
276             [ $self->param( $self->{authChoiceParam} ), $self->{authChoiceParam} ]
277             )
278             {
279             if ( $v->[0] ) {
280             $returnTo .= "$sep$v->[1]=$v->[0]";
281             $sep = '&';
282             }
283             }
284              
285             # ... and add it
286             $check_url .= '&openid.return_to=' . uri_escape_utf8($returnTo);
287              
288             # Now redirect user
289             print $self->redirect($check_url);
290             $self->quit();
291             }
292              
293             ## @apmethod int setAuthSessionInfo()
294             # Set _user and authenticationLevel.
295             # @return Lemonldap::NG::Portal constant
296             sub setAuthSessionInfo {
297             my $self = shift;
298              
299             $self->{sessionInfo}->{'_user'} = $self->{user};
300              
301             $self->{sessionInfo}->{authenticationLevel} = $self->{googleAuthnLevel};
302              
303             PE_OK;
304             }
305              
306             ## @apmethod int authenticate()
307             # Does nothing.
308             # @return Lemonldap::NG::Portal constant
309             sub authenticate {
310             PE_OK;
311             }
312              
313             ## @apmethod int authFinish()
314             # Does nothing.
315             # @return Lemonldap::NG::Portal constant
316             sub authFinish {
317             PE_OK;
318             }
319              
320             ## @apmethod int authLogout()
321             # Does nothing
322             # @return Lemonldap::NG::Portal constant
323             sub authLogout {
324             PE_OK;
325             }
326              
327             ## @apmethod boolean authForce()
328             # Does nothing
329             # @return result
330             sub authForce {
331             return 0;
332             }
333              
334             ## @method string getDisplayType
335             # @return display type
336             sub getDisplayType {
337             return "logo";
338             }
339              
340             1;
341             __END__
342              
343             =head1 NAME
344              
345             =encoding utf8
346              
347             Lemonldap::NG::Portal::AuthGoogle - Perl extension for building Lemonldap::NG
348             compatible portals with Google authentication.
349              
350             =head1 SYNOPSIS
351              
352             use Lemonldap::NG::Portal::SharedConf;
353             my $portal = new Lemonldap::NG::Portal::Simple(
354             configStorage => {...}, # See Lemonldap::NG::Portal
355             authentication => 'Google',
356             );
357              
358             if($portal->process()) {
359             # Write here the menu with CGI methods. This page is displayed ONLY IF
360             # the user was not redirected here.
361             print $portal->header('text/html; charset=utf-8'); # DON'T FORGET THIS (see CGI(3))
362             print "...";
363             }
364             else {
365             # If the user enters here, IT MEANS THAT CAS REDIRECTION DOES NOT WORK
366             print $portal->header('text/html; charset=utf-8'); # DON'T FORGET THIS (see CGI(3))
367             print "<html><body><h1>Unable to work</h1>";
368             print "This server isn't well configured. Contact your administrator.";
369             print "</body></html>";
370             }
371              
372             =head1 DESCRIPTION
373              
374             This library just overload few methods of Lemonldap::NG::Portal::Simple to use
375             Google authentication mechanism.
376              
377             See L<Lemonldap::NG::Portal::Simple> for usage and other methods.
378              
379             =head1 SEE ALSO
380              
381             L<Lemonldap::NG::Portal>, L<Lemonldap::NG::Portal::Simple>,
382             L<http://lemonldap-ng.org/>,
383             L<https://developers.google.com/accounts/docs/OpenID>
384              
385             =head1 AUTHOR
386              
387             =over
388              
389             =item Clement Oudot, E<lt>clem.oudot@gmail.comE<gt>
390              
391             =item Xavier Guimard, E<lt>x.guimard@free.frE<gt>
392              
393             =back
394              
395             =head1 BUG REPORT
396              
397             Use OW2 system to report bug or ask for features:
398             L<http://jira.ow2.org>
399              
400             =head1 DOWNLOAD
401              
402             Lemonldap::NG is available at
403             L<http://forge.objectweb.org/project/showfiles.php?group_id=274>
404              
405             =head1 COPYRIGHT AND LICENSE
406              
407             =over
408              
409             =item Copyright (C) 2013 by Xavier Guimard, E<lt>x.guimard@free.frE<gt>
410              
411             =item Copyright (C) 2013 by Clement Oudot, E<lt>clem.oudot@gmail.comE<gt>
412              
413             =back
414              
415             This library is free software; you can redistribute it and/or modify
416             it under the terms of the GNU General Public License as published by
417             the Free Software Foundation; either version 2, or (at your option)
418             any later version.
419              
420             This program is distributed in the hope that it will be useful,
421             but WITHOUT ANY WARRANTY; without even the implied warranty of
422             MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
423             GNU General Public License for more details.
424              
425             You should have received a copy of the GNU General Public License
426             along with this program. If not, see L<http://www.gnu.org/licenses/>.
427              
428             =cut
429