This commit was generated by cvs2svn to compensate for changes in r11022,
[freeside.git] / FS / FS / part_export / acct_google.pm
1 package FS::part_export::acct_google;
2
3 use strict;
4 use vars qw(%info %SIG $CACHE);
5 use Tie::IxHash;
6
7 use base 'FS::part_export';
8
9 tie my %options, 'Tie::IxHash',
10   'domain'    => { label => 'Domain name' },
11   'username'  => { label => 'Admin username' },
12   'password'  => { label => 'Admin password' },
13 ;
14 # To handle multiple domains, use separate instances of 
15 # the export.  We assume that they all have different 
16 # admin logins.
17
18 %info = (
19   'svc'       => 'svc_acct',
20   'desc'      => 'Google hosted mail',
21   'options'   => \%options,
22   'nodomain'  => 'Y',
23   'notes'    => <<'END'
24 Export accounts to the Google Provisioning API.  Requires 
25 REST::Google::Apps::Provisioning from CPAN.
26 END
27 );
28
29 sub rebless { shift; }
30
31 sub _export_insert {
32   my($self, $svc_acct) = (shift, shift);
33   $svc_acct->finger =~ /^(.*)\s+(\S+)$/;
34   my ($first, $last) = ($1, $2);
35   $self->google_request('createUser',
36     'username'      => $svc_acct->username,
37     'password'      => $svc_acct->_password,
38     'givenName'     => $first,
39     'familyName'    => $last,
40   );
41 }
42
43 sub _export_replace {
44   my( $self, $new, $old ) = (shift, shift, shift);
45   # We have to do this in two steps, so do the renameUser last so that 
46   # if it fails partway through the username is still coherent.
47   if ( $new->_password ne $old->_password
48     or $new->finger    ne $old->finger ) {
49     $new->finger =~ /^(.*)\s+(\S+)$/;
50     my ($first, $last) = ($1, $2);
51     my $error = $self->google_request('updateUser',
52       'username'    => $old->username,
53       'password'    => $new->_password,
54       'givenName'   => $first,
55       'familyName'  => $last,
56     );
57     return $error if $error;
58   }
59   if ( $new->username ne $old->username ) {
60     my $error = $self->google_request('renameUser',
61       'username'  => $old->username,
62       'newname'   => $new->username
63     );
64     return $error if $error;
65   }
66   return;
67 }
68
69 sub _export_delete {
70   my( $self, $svc_acct ) = (shift, shift);
71   $self->google_request('deleteUser',
72     'username'  => $svc_acct->username
73   );
74 }
75
76 sub _export_suspend {
77   my( $self, $svc_acct ) = (shift, shift);
78   $self->google_request('updateUser',
79     'username'  => $svc_acct->username,
80     'suspended' => 'true',
81   );
82 }
83
84 sub _export_unsuspend {
85   my( $self, $svc_acct ) = (shift, shift);
86   $self->google_request('updateUser',
87     'username'  => $svc_acct->username,
88     'suspended' => 'false',
89   );
90 }
91
92 sub captcha_url {
93   my $self = shift;
94   my $google = $self->google_handle;
95   if (exists ($google->{'captcha_url'}) ) {
96     return 'http://www.google.com/accounts/'.$google->{'captcha_url'};
97   }
98   else {
99     return '';
100   }
101 }
102
103 sub captcha_auth {
104   my $self = shift;
105   my $response = shift;
106   my $google = $self->google_handle('captcha_response' => $response);
107   return (defined($google->{'token'}));
108 }
109
110 my %google_error = (
111   1000 => 'unknown error',
112   1001 => 'server busy',
113   1100 => 'username belongs to a recently deleted account',
114   1101 => 'user suspended',
115   1200 => 'domain user limit exceeded',
116   1201 => 'domain alias limit exceeded',
117   1202 => 'domain suspended',
118   1203 => 'feature not available on this domain',
119   1300 => 'username in use',
120   1301 => 'user not found',
121   1302 => 'reserved username',
122   1400 => 'illegal character in first name',
123   1401 => 'illegal character in last name',
124   1402 => 'invalid password',
125   1403 => 'illegal character in username',
126   # should be everything we need
127 );
128
129 # Runs the request and returns nothing if it succeeds, or an 
130 # error message.
131
132 sub google_request {
133   my ($self, $method, %opt) = @_;
134   my $google = $self->google_handle(
135     'captcha_response' => delete $opt{'captcha_response'}
136   );
137   return $google->{'error'} if $google->{'error'};
138
139   # Throw away the result from this; we don't use it yet.
140   eval { $google->$method(%opt) };
141   if ( $@ ) {
142     return $google_error{ $@->{'error'}->{'errorCode'} } || $@->{'error'};
143   }
144   return;
145 }
146
147 # Returns a REST::Google::Apps::Provisioning object which is hooked 
148 # to die {error => stuff} on API errors.  The cached auth token 
149 # will be used if possible.  If not, try to authenticate.  On 
150 # authentication error, the R:G:A:P object will still be returned 
151 # but with $google->{'error'} set to the error message.
152
153 sub google_handle {
154   my $self = shift;
155   my %opt = @_;
156   my @class = ( 
157     'REST::Google::Apps::Provisioning',
158     'Cache::FileCache',
159     'LWP::UserAgent 5.815',
160   );
161   foreach (@class) {
162     eval "use $_";
163     die "failed to load $_\n" if $@;
164   }
165   $CACHE ||= new Cache::FileCache( {
166       'namespace'   => __PACKAGE__,
167       'cache_root'  => "$FS::UID::cache_dir/cache.$FS::UID::datasrc",
168   } );
169   my $google = REST::Google::Apps::Provisioning->new(
170     'domain'  => $self->option('domain') 
171   );
172
173   # REST::Google::Apps::Provisioning lacks error reporting.  We deal 
174   # with that by hooking HTTP::Response to throw a useful fatal error 
175   # on failure.
176   $google->{'lwp'}->add_handler( 'response_done' =>
177     sub {
178       my $response = shift;
179       return if $response->is_success;
180
181       my $error = '';
182       if ( $response->content =~ /^</ ) {
183         #presume xml
184         $error = $google->{'xml'}->parse_string($response->content);
185       }
186       elsif ( $response->content =~ /=/ ) {
187         $error = +{ map { if ( /^(\w+)=(.*)$/ ) { lc($1) => $2 } }
188           split("\n", $response->content)
189         };
190       }
191       else { # have something to say if there is no response...
192         $error = {'error' => $response->status_line};
193       }
194       die $error;
195     }
196   );
197
198   my $cache_token = $self->exportnum . '_token';
199   my $cache_captcha = $self->exportnum . '_captcha_token';
200   $google->{'token'} = $CACHE->get($cache_token);
201   if ( !$google->{'token'} ) {
202     my %login = (
203       'username' => $self->option('username'),
204       'password' => $self->option('password'),
205     );
206     if ( $opt{'captcha_response'} ) {
207       $login{'logincaptcha'} = $opt{'captcha_response'};
208       $login{'logintoken'} = $CACHE->get($cache_captcha);
209     }
210     eval { $google->captcha_auth(%login); };
211     if ( $@ ) {
212       $google->{'error'} = $@->{'error'};
213       $google->{'captcha_url'} = $@->{'captchaurl'};
214       $CACHE->set($cache_captcha, $@->{'captchatoken'}, '1 minute');
215       return $google;
216     }
217     $CACHE->remove($cache_captcha);
218     $CACHE->set($cache_token, $google->{'token'}, '1 hour');
219   }
220   return $google;
221 }
222
223 # REST::Google::Apps::Provisioning also lacks a way to do this
224 sub REST::Google::Apps::Provisioning::captcha_auth {
225   my $self = shift;
226
227   return( 1 ) if $self->{'token'};
228
229   my ( $arg );
230   %{$arg} = @_;
231
232   map { $arg->{lc($_)} = $arg->{$_} } keys %{$arg};
233
234   foreach my $param ( qw/ username password / ) {
235     $arg->{$param} || croak( "Missing required '$param' argument" );
236   }
237
238   my @postargs = (
239     'accountType' => 'HOSTED',
240     'service'     => 'apps',
241     'Email'       => $arg->{'username'} . '@' . $self->{'domain'},
242     'Passwd'      => $arg->{'password'},
243   );
244   if ( $arg->{'logincaptcha'} ) {
245     push @postargs, 
246       'logintoken'  => $arg->{'logintoken'},
247       'logincaptcha'=> $arg->{'logincaptcha'}
248       ;
249   }
250   my $response = $self->{'lwp'}->post(
251     'https://www.google.com/accounts/ClientLogin',
252     \@postargs
253   );
254
255   $response->is_success() || return( 0 );
256
257   foreach ( split( /\n/, $response->content() ) ) {
258     $self->{'token'} = $1 if /^Auth=(.+)$/;
259     last if $self->{'token'};
260   }
261
262   return( 1 ) if $self->{'token'} || return( 0 );
263 }
264
265 1;