VUser-Google-Api-1.0.1/ 0000755 0001750 0001750 00000000000 11570731200 014374 5 ustar rbsmith rbsmith VUser-Google-Api-1.0.1/lib/ 0000755 0001750 0001750 00000000000 11570731200 015142 5 ustar rbsmith rbsmith VUser-Google-Api-1.0.1/lib/VUser/ 0000755 0001750 0001750 00000000000 11570731200 016206 5 ustar rbsmith rbsmith VUser-Google-Api-1.0.1/lib/VUser/Google/ 0000755 0001750 0001750 00000000000 11570731200 017422 5 ustar rbsmith rbsmith VUser-Google-Api-1.0.1/lib/VUser/Google/ProvisioningAPI/ 0000755 0001750 0001750 00000000000 11570731200 022442 5 ustar rbsmith rbsmith VUser-Google-Api-1.0.1/lib/VUser/Google/ProvisioningAPI/V2_0/ 0000755 0001750 0001750 00000000000 11570731200 023150 5 ustar rbsmith rbsmith VUser-Google-Api-1.0.1/lib/VUser/Google/ProvisioningAPI/V2_0/EmailListEntry.pm 0000644 0001750 0001750 00000002337 11570726507 026436 0 ustar rbsmith rbsmith package VUser::Google::ProvisioningAPI::V2_0::EmailListEntry;
use warnings;
use strict;
use vars qw($AUTOLOAD);
use Carp;
our $VERSION = '0.2.0';
sub new {
my $object = shift;
my $class = ref($object) || $object;
my $self = {
'EmailList' => shift
};
bless $self, $class;
return $self;
}
sub DESTROY { };
sub AUTOLOAD {
my $self = shift;
my $member = $AUTOLOAD;
$member =~ s/.*:://;
if (exists $self->{$member}) {
$self->{$member} = $_[0] if defined $_[0];
return $self->{$member};
} else {
croak "Unknown member: $member";
}
}
=pod
=head1 NAME
VUser::Google::ProvisioningAPI::V2_0::EmailListEntry - Google Provisioning API 2.0 email list entry
=head1 SYNOPSIS
my $entry = VUser::Google::ProvisioningAPI::V2_0::EmailListEntry->new();
$entry->EmailList('bar');
=head1 ACCESSORS
=over
=item EmailList
=back
=head1 AUTHOR
Randy Smith, perlstalker at vuser dot org
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2007 by Randy Smith, perlstalker at vuser dot org
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
=cut
1;
VUser-Google-Api-1.0.1/lib/VUser/Google/ProvisioningAPI/V2_0/EmailListRecipientEntry.pm 0000644 0001750 0001750 00000002475 11570726507 030304 0 ustar rbsmith rbsmith package VUser::Google::ProvisioningAPI::V2_0::EmailListRecipientEntry;
use warnings;
use strict;
use vars qw($AUTOLOAD);
use Carp;
our $VERSION = '0.2.0';
sub new {
my $object = shift;
my $class = ref($object) || $object;
my $self = {
'EmailList' => shift,
'Who' => shift
};
bless $self, $class;
return $self;
}
sub DESTROY { };
sub AUTOLOAD {
my $self = shift;
my $member = $AUTOLOAD;
$member =~ s/.*:://;
if (exists $self->{$member}) {
$self->{$member} = $_[0] if defined $_[0];
return $self->{$member};
} else {
croak "Unknown member: $member";
}
}
=pod
=head1 NAME
VUser::Google::ProvisioningAPI::V2_0::EmailListRecipientEntry - Google Provisioning API 2.0 email list recipient entry
=head1 SYNOPSIS
my $entry = VUser::Google::ProvisioningAPI::V2_0::EmailListRecipientEntry->new();
$entry->EmailList('foo');
$entry->Who('bar@baz.com');
=head1 ACCESSORS
=over
=item EmailList
=item Who
=back
=head1 AUTHOR
Randy Smith, perlstalker at vuser dot org
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2007 by Randy Smith, perlstalker at vuser dot org
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
=cut
1;
VUser-Google-Api-1.0.1/lib/VUser/Google/ProvisioningAPI/V2_0/UserEntry.pm 0000644 0001750 0001750 00000006120 11570726507 025463 0 ustar rbsmith rbsmith package VUser::Google::ProvisioningAPI::V2_0::UserEntry;
use warnings;
use strict;
use vars qw($AUTOLOAD);
use Carp;
our $VERSION = '0.2.0';
sub new {
my $object = shift;
my $class = ref($object) || $object;
#LP: changePasswordAtNextLogin
my ($user, $password, $family_name, $given_name, $quota, $email, $isSuspended, $changePasswordAtNextLogin, $hashFunctionName);
if (defined $isSuspended) {
$isSuspended = ($isSuspended)? '1' : '0';
}
#LP: changePasswordAtNextLogin
if (defined $changePasswordAtNextLogin) {
$changePasswordAtNextLogin = ($changePasswordAtNextLogin)? '1' : '0';
}
# This doesn't quite match the Java API but I don't really care right now.
# This is much easier. Perhaps, at some point in the future, this can
# be changed to match the Java API a little more.
my $self = {
'User' => $user,
'Password' => $password,
'isSuspended' => $isSuspended,
'FamilyName' => $family_name,
'GivenName' => $given_name,
'Email' => $email,
'Quota' => $quota,
#LP: changePasswordAtNextLogin
'changePasswordAtNextLogin' => $changePasswordAtNextLogin,
'hashFunctionName' => $hashFunctionName,
};
bless $self, $class;
return $self;
}
# Alias to match the Java API a little more
sub Suspended { $_[0]->isSuspended(@_); }
sub isSuspended {
my $self = shift;
my $suspended = shift;
if (defined $suspended) {
if (lc($suspended) eq 'false') {
$self->{'isSuspended'} = 0;
} elsif (not $suspended) {
$self->{'isSuspended'} = 0;
} else {
$self->{'isSuspended'} = 1;
}
}
return $self->{'isSuspended'};
}
#LP: changePasswordAtNextLogin
sub changePasswordAtNextLogin {
my $self = shift;
my $changePassword = shift;
if (defined $changePassword) {
if (lc($changePassword) eq 'false') {
$self->{'changePasswordAtNextLogin'} = 0;
} elsif (not $changePassword) {
$self->{'changePasswordAtNextLogin'} = 0;
} else {
$self->{'changePasswordAtNextLogin'} = 1;
}
}
return $self->{'changePasswordAtNextLogin'};
}
sub DESTROY { };
sub AUTOLOAD {
my $self = shift;
my $member = $AUTOLOAD;
$member =~ s/.*:://;
if (exists $self->{$member}) {
$self->{$member} = $_[0] if defined $_[0];
return $self->{$member};
} else {
croak "Unknown member: $member";
}
}
=pod
=head1 NAME
VUser::Google::ProvisioningAPI::V2_0::UserEntry - Google Provisioning API 2.0 User entry
=head1 SYNOPSIS
my $entry = VUser::Google::ProvisioningAPI::V2_0::UserEntry->new();
$entry->User('foo'); # set the user name to 'foo'
$entry->GivenName('Fred');
$entry->FamilyName('Oog');
=head1 ACCESSORS
=over
=item User
=item Password
=item isSuspended
=item FamilyName
=item GivenName
=item Email
=item Quota
=back
=head1 AUTHOR
Randy Smith, perlstalker at vuser dot org
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2007 by Randy Smith, perlstalker at vuser dot org
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
=cut
1;
VUser-Google-Api-1.0.1/lib/VUser/Google/ProvisioningAPI/V2_0/NicknameEntry.pm 0000644 0001750 0001750 00000002451 11570726507 026275 0 ustar rbsmith rbsmith package VUser::Google::ProvisioningAPI::V2_0::NicknameEntry;
use warnings;
use strict;
use vars qw($AUTOLOAD);
use Carp;
our $VERSION = '0.2.0';
sub new {
my $object = shift;
my $class = ref($object) || $object;
my $self = {
'User' => shift,
'Nickname' => shift
};
bless $self, $class;
return $self;
}
sub DESTROY { };
sub AUTOLOAD {
my $self = shift;
my $member = $AUTOLOAD;
$member =~ s/.*:://;
if (exists $self->{$member}) {
$self->{$member} = $_[0] if defined $_[0];
return $self->{$member};
} else {
croak "Unknown member: $member";
}
}
=pod
=head1 NAME
VUser::Google::ProvisioningAPI::V2_0::NicknameEntry - Google Provisioning API 2.0 nick name entry
=head1 SYNOPSIS
my $entry = VUser::Google::ProvisioningAPI::V2_0::NicknameEntry->new();
$entry->User('foo'); # set the user name to 'foo'
$entry->Nickname('bar');
=head1 ACCESSORS
=over
=item User
=item Nickname
=back
=head1 AUTHOR
Randy Smith, perlstalker at vuser dot org
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2007 by Randy Smith, perlstalker at vuser dot org
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
=cut
1;
VUser-Google-Api-1.0.1/lib/VUser/Google/ProvisioningAPI/V1_0.pm 0000644 0001750 0001750 00000077623 11570726507 023542 0 ustar rbsmith rbsmith #A class that encapsulates the Google Apps for Your Domain Provisioning API V1.0
#see http://code.google.com/apis/apps-for-your-domain/google_apps_provisioning_api_v1.0_reference.html
#(C) 2006 Johan Reinalda, johan at reinalda dot net
#
#skeleton generated with h2xs -AXc -n Google::ProvisioningAPI
#
package VUser::Google::ProvisioningAPI::V1_0;
use 5.008005;
use strict;
use warnings;
use vars qw($VERSION);
use Carp;
use LWP::UserAgent qw(:strict);
use HTTP::Request qw(:strict);
use Encode;
use XML::Simple;
#I don't see the need for this - JKR
#require Exporter;
#NOT NEEDED FOR THIS CLASS
#our @ISA = qw(Exporter AutoLoader);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
# This allows declaration use VUser::Google::ProvisioningAPI ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
#I don't see the need for this - JKR
#our %EXPORT_TAGS = ( 'all' => [ qw(
#
#) ] );
#
#our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
#
#our @EXPORT = qw(
#
#);
our $VERSION = '0.11';
our $APIVersion = '1.0';
#some constants
#web agent identification
use constant GOOGLEAGENT => "Google_ProvisioningAPI-perl/$VERSION";
#url for Google API token login
use constant GOOGLEHOST => 'www.google.com';
use constant GOOGLETOKENURL => 'https://www.google.com/accounts/ClientLogin';
use constant MAXTOKENAGE => 24 * 60 * 60; #24 hours, see API docs
#base url to the Google REST API
use constant GOOGLEBASEURL => 'https://www.google.com/a/services/v1.0/';
use constant SUCCESSCODE => 'Success(2000)';
use constant FAILURECODE => 'Failure(2001)';
#some size constants
use constant MAXNAMELEN => 40;
use constant MAXUSERNAMELEN => 30;
# Preloaded methods go here.
#the constructor
sub new
{
#parse parameters, if any
(@_ == 4) || croak 'Constructor takes 3 arguments: domain, admin, adminpassword';
my $object = shift();
my $class = ref($object) || $object;
my $self = {
#Google related variables
domain => shift(), #the Google hosted domain we are accessing
admin => shift(), #the account to use when authenticating
password => shift(), #the password to use when authenticating
refreshtoken => 0, #if set, will force a re-authentication
authtoken => '', #the authentication token returned from google
authtime => 0, #time when authentication happened; only valid for 24 hours
requestcontent => '', #the last http content posted to Google
replyheaders => '', #the http headers of the last reply
replycontent => '', #the http content of the last reply
result => {}, #the resulting hash from the last reply data as parsed by XML::Simple
#some other variables
debug => 0, #when turned on, will spit out debug info to STDERR
#some statistics that are 'read-only'
stats => {
ctime => time, #object creation time
rtime => 0, #time of last request
requests => 0, #number of API requests made
success => 0, #number of successes
logins => 0, #number of authentications performed
}
};
#return object
bless( $self, 'VUser::Google::ProvisioningAPI::V1_0');
return $self;
}
#method used to (re)login to the API, either first time, or as token times out
sub Relogin
{
#get object reference
my $self = shift();
$self->dprint("Relogin called\n");
my $retval = 0;
#adjust stats counter
$self->{stats}->{logins}++;
#clear last results
$self->{replyheaders} = $self->{replycontent} = '';
$self->{result} = {};
# Create an LWP object to make the HTTP POST request
my $lwp = LWP::UserAgent->new;
if(defined($lwp)) {
$lwp->agent(GOOGLEAGENT);
$lwp->from($self->{admin}.'@'.$self->{domain});
# Submit the request with values for
# accountType, Email and Passwd variables.
my $response = $lwp->post( GOOGLETOKENURL,
[ 'accountType' => 'HOSTED',
'Email' => $self->{admin}.'@'.$self->{domain},
'Passwd' => $self->{password}
]
);
#save reply page
$self->{replyheaders} = $response->headers->as_string;
$self->{replycontent} = $response->content;
if ($response->is_success) {
# Extract the authentication token from the response
foreach my $line (split/\n/, $response->content) {
#$self->dprint( "RECV'd: $line" );
if ($line =~ m/^SID=(.+)$/) {
$self->{authtoken} = $1;
$self->{authtime} = time;
$self->dprint("Token found: $self->{authtoken}\n");
#clear refresh
$self->{refreshtoken} = 0;
$retval = 1;
last;
}
}
}
else {
$self->dprint("Error in login: " . $response->status_line . "\n");
$self->{result}->{reason} = "Error in login: " . $response->status_line;
}
} else {
$self->dprint("Error getting lwp object: $!\n");
$self->{result}->{reason} = "Error getting lwp object: $!";
}
return $retval;
}
#check if we are authenticated. If not, try to re-login
sub IsAuthenticated {
#get object reference
my $self = shift();
if( $self->{refreshtoken} or ( (time - $self->{authtime}) > MAXTOKENAGE ) ) {
return $self->Relogin();
}
#we are still okay!
return 1;
}
#generic request routine that handles most functionality
#requires 3 arguments: Type, Action, Body
#Type is the object type to action upon. ('Account', 'Alias', 'MailingList')
#Action is what needs to be done
#Body is the xml specific to the action
sub Request
{
my $retval = 0;
#get object reference
my $self = shift();
$self->dprint( "***REQUEST***\n");
#clear last results
$self->{replyheaders} = $self->{replycontent} = '';
$self->{result} = {};
if(@_ != 3) {
$self->{result}->{reason} = 'Invalid number of arguments to request()';
return 0;
}
#get parameters
my($type,$action,$body) = @_;
$self->dprint( "Type: $type\nAction: $action\n$body\n");
#keep some stats
$self->{stats}->{requests}++;
$self->{stats}->{rtime} = time;
#check if we are authenticated to google
if(!$self->IsAuthenticated()) {
$self->dprint( "Error authenticating\n");
return 0;
}
#standard XML pre and post segments
my $pre = <<"EOL";
$type<\/hs:type>
$self->{authtoken}$self->{domain}
EOL
my $post = '';
#create to request body
$body = $pre . $body . $post;
#properly encode it
$body = encode('UTF-8',$body);
#save the request content
$self->{requestcontent} = $body;
# Create an LWP object to make the HTTP POST request over
my($ua) = LWP::UserAgent->new;
if(!defined($ua)) {
$self->dprint("Cannot create LWP::UserAgent object: $!\n");
$self->{result}->{reason} = "Cannot create LWP::UserAgent object in request(): $!";
return $retval;
}
#and create the request object where are we connecting to
my $url = GOOGLEBASEURL . $action;
$self->dprint("URL: $url\n");
my $req = HTTP::Request->new(POST => $url);
if(!defined($req)) {
$self->dprint("Cannot create HTTP::Request object: $!\n");
$self->{result}->{reason} = "Cannot create HTTP::Request object in request(): $!";
return $retval;
}
#set some user agent variables
$ua->agent( GOOGLEAGENT );
$ua->from( '<' . $self->{admin}.'@'.$self->{domain} . '>');
# Submit the request with values for
# accountType, Email and Passwd variables.
#$req->header('ContentType' => 'application/x-www-form-urlencoded');
$req->header('Content-Type' => 'application/xml');
$req->header('Accept' => 'application/xml');
$req->header('Content-Lenght' => length($body) );
$req->header('Connection' => 'Keep-Alive');
$req->header('Host' => GOOGLEHOST);
#assign the data to the request
$req->content($body);
#execute the request
my $response = $ua->request($req);
#save reply page
$self->{replyheaders} = $response->headers->as_string;
$self->{replycontent} = $response->content;
#check result
if ($response->is_success) {
$self->{stats}->{success}++;
$self->dprint( "Success in post:\n");
#delete all namespace elements to keep it simple (ie. remove "hs:")
#this avoids the need to use XML::NameSpace
my $xml = decode('UTF-8', $response->content);
$xml =~ s/hs\://g;
$self->dprint( $xml );
#now go parse it using XML::Simple
$self->{result} = XMLin($xml,ForceArray => 0);
#include Data::Dumper above if you want to use this line:
#$self->dprint( Dumper($self->{result}) );
#see if this was a successful call
if( defined($self->{result}->{status}) and $self->{result}->{status} eq SUCCESSCODE ) {
$self->dprint("Google API success!");
$retval = 1;
} else {
$self->dprint("Google API failure!");
if(defined($self->{result}->{reason})) {
$@ = "Google API failure: $self->{result}->{status} - $self->{result}->{reason}";
} else {
$@ = "Google API failure: reason not found!";
$self->{result}->{reason} = "Google API failure: reason not found!";
}
}
}
else {
$self->dprint( "Error in post: " . $response->status_line . "\n");
$self->{result}->{reason} = "Error in http post: " . $response->status_line;
}
#show full response for now
#$self->dprint( "Headers:\n" . $response->headers->as_string);
#foreach my $line (split/\n/, $response->content) {
# $self->dprint( "RECV'd: $line\n");
#}
return $retval;
}
######################################
### these are the actual API calls ###
### See the Google docs for more ###
######################################
### HOSTED ACCOUNT routines ###
sub CreateAccountEmail
{
#get object reference
my $self = shift();
$self->dprint( "CreateAccount called\n");
#check remaining arguments
if(@_ < 4) {
$self->dprint( "CreateAccountEmail method requires at least 4 arguments!\n");
$self->{result}->{reason} = "CreateAccountEmail method requires at least 4 arguments!";
return 0;
}
#get arguments
my $userName = shift();
my $firstName = shift();
my $lastName = shift();
my $password = shift();
my $quota = shift() if (@_); #this one is optional
my $body = <<"EOL";
$firstName$lastName$password$userName
EOL
if(defined($quota)) {
$body .= "\t\t$quota<\/hs:quota>\n";
}
#add the final end-of-section tab
$body .= "\t<\/hs:CreateSection>\n";
return $self->Request('Account','Create/Account/Email',$body);
}
#NOTE: this API call may be discontinued!
sub CreateAccount
{
#get object reference
my $self = shift();
$self->dprint( "CreateAccount called\n");
#check remaining arguments
if(@_ != 4) {
$self->dprint( "CreateAccount method requires 4 arguments!\n");
$self->{result}->{reason} = "CreateAccount method requires 4 arguments!";
return 0;
}
#get arguments
my $userName = shift();
my $firstName = shift();
my $lastName = shift();
my $password = shift();
my $body = <<"EOL";
$firstName$lastName$password$userName
EOL
return $self->Request('Account','Create/Account',$body);
}
sub UpdateAccount
{
#get object reference
my $self = shift();
$self->dprint( "UpdateAccount called\n");
#check remaining arguments
if(@_ != 4) {
$self->dprint( "UpdateAccount method requires 4 arguments!\n");
$self->{result}->{reason} = "UpdateAccount method requires 4 arguments!";
return 0;
}
#get arguments
my $userName = shift();
my $firstName = shift();
my $lastName = shift();
my $password = shift();
#build request body
my $body = <<"EOL";
userName$userName
EOL
if(defined($firstName)) {
$body .= "\t\t$firstName<\/hs:firstName>\n";
}
if(defined($lastName)) {
$body .= "\t\t$lastName<\/hs:lastName>\n";
}
if(defined($password)) {
$body .= "\t\t$password<\/hs:password>\n";
}
#add the final end-of-section tab
$body .= "\t<\/hs:UpdateSection>\n";
return $self->Request('Account','Update/Account',$body);
}
sub UpdateAccountEmail
{
#get object reference
my $self = shift();
$self->dprint( "UpdateAccountEmail called\n");
#check remaining arguments
if(@_ != 1) {
$self->dprint( "UpdateAccount method requires 1 argument!\n");
$self->{result}->{reason} = "CreateAccount method requires 1 argument!";
return 0;
}
#get arguments
my $userName = shift();
my $body = <<"EOL";
userName$userName1
EOL
return $self->Request('Account','Update/Account/Email',$body);
}
sub UpdateAccountStatus
{
#get object reference
my $self = shift();
$self->dprint( "UpdateAccountStatus called\n");
#check remaining arguments
if(@_ != 2) {
$self->dprint( "UpdateAccount method requires 2 argument!\n");
$self->{result}->{reason} = "CreateAccount method requires 2 arguments!";
return 0;
}
#get arguments
my $userName = shift();
my $status = shift();
if($status ne 'locked' and $status ne 'unlocked') {
$self->dprint( "Error: status invalid!\n");
$self->{result}->{reason} = 'Invalid status';
return 0;
}
my $body = <<"EOL";
userName$userName$status
EOL
return $self->Request('Account','Update/Account/Status',$body);
}
sub RetrieveAccount
{
#get object reference
my $self = shift();
$self->dprint( "RetrieveAccount called\n");
#check remaining arguments
if(@_ != 1) {
$self->dprint( "RetrieveAccount method requires 1 argument!\n");
$self->{result}->{reason} = "RetrieveAccount method requires 1 argument!";
return 0;
}
#get argument
my $userName = shift();
my $body = <<"EOL";
userName$userName
EOL
return $self->Request('Account','Retrieve/Account',$body);
}
sub DeleteAccount
{
#get object reference
my $self = shift();
$self->dprint( "DeleteAccount called\n");
#check remaining arguments
if(@_ != 1) {
$self->dprint( "DeleteAccount method requires 1 argument!\n");
$self->{result}->{reason} = "DeleteAccount method requires 1 argument!";
return 0;
}
#get argument
my $userName = shift();
my $body = <<"EOL";
userName$userName
EOL
return $self->Request('Account','Delete/Account',$body);
}
sub RenameAccount
{
#This is derived from the Python sample code:
#-----
#Username change. Note that this feature must be explicitly
# enabled by the domain administrator, and is not enabled by
# default.
#
# Args:
# oldname: user to rename
# newname: new username to set for the user
# alias: if 1, create an alias of oldname for newname
#-----
#Ie. this may not work yet - JKR 20061204
#get object reference
my $self = shift();
$self->dprint( "RenameAccount called\n");
#check remaining arguments
if(@_ != 3) {
$self->dprint( "RenameAccount method requires 3 arguments!\n");
$self->{result}->{reason} = "RenameAccount method requires 3 arguments!";
return 0;
}
#get arguments
my $oldName = shift();
my $newName = shift();
my $alias = shift();
#check format of alias; default to 0
$alias = lc($alias);
if($alias ne '1') { $alias = '0'; }
#build request format
my $body = <<"EOL";
userName$oldName$newName$alias
EOL
return $self->Request('Account','Update/Account/Username',$body);
}
### ALIAS routines ###
sub CreateAlias
{
#get object reference
my $self = shift();
$self->dprint( "CreateAlias called\n");
#check remaining arguments
if(@_ != 2) {
$self->dprint( "CreateAlias method requires 2 arguments!\n");
$self->{result}->{reason} = "CreateAlias method requires 2 arguments!";
return 0;
}
#get argument
my $userName = shift();
my $alias = shift();
#create the command format
my $body = <<"EOL";
$userName$alias
EOL
return $self->Request('Alias','Create/Alias',$body);
}
sub RetrieveAlias
{
#get object reference
my $self = shift();
$self->dprint( "RetrieveAlias called\n");
#check remaining arguments
if(@_ != 1) {
$self->dprint( "RetrieveAlias method requires 1 argument!\n");
$self->{result}->{reason} = "RetrieveAlias method requires 1 argument!";
return 0;
}
#get argument
my $userName = shift();
my $body = <<"EOL";
aliasName$userName
EOL
return $self->Request('Alias','Retrieve/Alias',$body);
}
sub DeleteAlias
{
#get object reference
my $self = shift();
$self->dprint( "DeleteAlias called\n");
#check remaining arguments
if(@_ != 1) {
$self->dprint( "DeleteAlias method requires 1 argument!\n");
$self->{result}->{reason} = "DeleteAlias method requires 1 argument!";
return 0;
}
#get arguments
my $alias = shift();
my $body = <<"EOL";
aliasName$alias
EOL
return $self->Request('Alias','Delete/Alias',$body);
}
### Mailing List routines
sub CreateMailingList
{
#get object reference
my $self = shift();
$self->dprint( "CreateMailingList called\n");
#check remaining arguments
if(@_ != 1) {
$self->dprint( "CreateMailingList method requires 1 argument!\n");
$self->{result}->{reason} = "CreateMailingList method requires 1 argument!";
return 0;
}
#get arguments
my $mailingListName = shift();
my $body = <<"EOL";
$mailingListName
EOL
return $self->Request('MailingList','Create/MailingList',$body);
}
sub UpdateMailingList
{
#get object reference
my $self = shift();
$self->dprint( "UpdateMailingList called\n");
#check remaining arguments
if(@_ != 3) {
$self->dprint( "UpdateMailingList method requires 3 arguments!\n");
$self->{result}->{reason} = 'UpdateMailingList method requires 3 arguments!';
return 0;
}
#get arguments
my $mailingListName = shift();
my $userName = shift();
my $listOperation = shift();
my $body = <<"EOL";
mailingListName$mailingListName$userName$listOperation
EOL
return $self->Request('MailingList','Update/MailingList',$body);
}
sub RetrieveMailingList
{
#get object reference
my $self = shift();
$self->dprint( "RetrieveMailingList called\n");
#check remaining arguments
if(@_ != 1) {
$self->dprint( "RetrieveMailingList method requires 1 argument!\n");
$self->{result}->{reason} = 'RetrieveMailingList method requires 1 arguments!';
return 0;
}
#get argument
my $mailingListName = shift();
my $body = <<"EOL";
mailingListName$mailingListName
EOL
return $self->Request('MailingList','Retrieve/MailingList',$body);
}
sub DeleteMailingList
{
#get object reference
my $self = shift();
$self->dprint( "DeleteMailingList called\n");
#check remaining arguments
if(@_ != 1) {
$self->dprint( "DeleteMailingList method requires 1 argument!\n");
$self->{result}->{reason} = 'DeleteMailingList method requires 1 argument!';
return 0;
}
#get argument
my $mailingListName = shift();
my $body = <<"EOL";
mailingListName$mailingListName
EOL
return $self->Request('MailingList','Delete/MailingList',$body);
}
################################################################
# below are various subroutines to access local 'private' data #
################################################################
#the content of the request from and reply from Google API engine
sub requestcontent
{
my $self = shift();
return $self->{requestcontent};
}
sub replyheaders
{
my $self = shift();
return $self->{replyheaders};
}
sub replycontent
{
my $self = shift();
return $self->{replycontent};
}
#various access to local variables
sub debug
{
my $self = shift();
$self-> { debug } = shift() if (@_);
return $self->{debug};
}
#change the admin account
sub admin
{
my $self = shift();
if (@_)
{
$self-> { admin } = shift();
$self-> { refreshtoken } = 1;
}
return $self->{admin};
}
#password can only be set, not read!
sub password
{
my $self = shift();
if (@_)
{
$self-> { password } = shift();
#force authentication update on next request
$self-> { refreshtoken } = 1;
}
return '';
}
#the following can only be read!
sub authtime
{
my $self = shift();
return $self->{authtime};
}
#same for create time
sub ctime
{
my $self = shift();
return $self->{stats}->{ctime};
}
#and request time
sub rtime
{
my $self = shift();
return $self->{stats}->{rtime};
}
sub requests
{
my $self = shift();
return $self->{stats}->{requests};
}
sub logins
{
my $self = shift();
return $self->{stats}->{logins};
}
sub success
{
my $self = shift();
return $self->{stats}->{success};
}
sub version
{
my $self = shift();
return $APIVersion;
}
#several helper routines
#print out debugging to STDERR if debug is set
sub dprint
{
my $self = shift();
my($text) = shift if (@_);
if( $self->{debug} and defined ($text) ) {
print STDERR $text . "\n";
}
}
1;
__END__
=pod
=head1 NAME
VUser::Google::ProvisioningAPI::V1_0 - Perl module that implements version 1.0 of the Google Apps for Your Domain Provisioning API
=head1 SYNOPSIS
use VUser::Google::ProvisioningAPI;
my $google = new VUser::Google::ProvisioningAPI($domain,$admin,$password);
$google->CreateAccount($userName, $firstName, $lastName, $password);
$google->RetrieveAccount($userName);
=head1 REQUIREMENTS
VUser::Google::ProvisioningAPI requires the following modules to be installed:
=over
=item
C
=item
C
=item
C
=item
C
=back
=head1 DESCRIPTION
VUser::Google::ProvisioningAPI provides a simple interface to the Google Apps for Your Domain Provisioning API.
It uses the C module for the HTTP transport, and the C module for the HTTP request and response.
=head2 Examples
For a complete description of the meaning of the following methods, see the Google API documentation referenced in the SEE ALSO section.
#create the object
$google = new Google:ProvisioningAPI($domain,$admin,$password) || die "Cannot create google object";
print 'Module version: ' . $google->VERSION . "\nAPI Version: " . $google->version() . "\n";
#create a hosted account
if( $google->CreateAccount( $userName, $firstName, $lastName, $password ) )
{
print "Account created!\N";
}
#add email services to the account
$google->UpdateAccountEmail($userName);
#retrieving account data
if($google->RetrieveAccount($userName))
{
print 'Username: ' . $google->{result}->{RetrievalSection}->{userName} . "\n";
print 'firstName: ' . $google->{result}->{RetrievalSection}->{firstName} . "\n";
print 'lastName: ' . $google->{result}->{RetrievalSection}->{lastName} . "\n";
print 'accountStatus: ' . $google->{result}->{RetrievalSection}->{accountStatus} . "\n";
}
#see what the result hash after a request looks like
use Data::Dumper;
print Dumper($google->{result});
#delete an account
$ret = DeleteAccount($userName);
#accessing the HTML data as it was received from the Google servers:
print $google->replyheaders();
print $google->replycontent();
=head1 CONSTRUCTOR
new ( $domain, $admin, $adminpassword )
This is the constructor for a new VUser::Google::ProvisioningAPI object.
$domain is the domain name registered with Google Apps For Your Domain,
$admin is an account in the above domain that has the right to manage that domain, and
$adminpassword is the password for that account.
Note that the constructor will NOT attempt to perform the 'ClientLogin' call to the Google Provisioning API (see below).
Authentication happens automatically when the first API call is performed. The token will be remembered for the duration of the object, and will be automatically refreshed as needed.
If you want to verify that you can get a valid token before performing any operations, follow the constructor with a call to IsAuthenticated() as such:
print "Authentication OK\n" unless not $google->IsAuthenticated();
=head1 METHODS
Below are all the methods available on the object. For the Google API specific methods, see the Google API documentation for more details.
When a request is properly handled by Google's API engine, the webpost to the API succeeds. This results in a valid page being returned. The content of this page then defines whether the request succeeded or not.
All pages returing the 'Success(2000)' status code will result in the API method succeeding, and returning a 1. All failures return 0.
Please see the section below on how to access the result data, and how to determine the reasons for errors.
If the web post fails (as determined by the C method IsSuccess() ), the method returns 0, and the {reason} hash is set to a descriptive error.
You can then examine the raw data to get an idea of what went wrong.
=head2 Checking Authentication
IsAuthenticated()
=over
will check if the object has been able to authenticate with Google's api engine, and get an authentication ticket.
Returns 1 if successful, 0 on failure. To see why it may fail, see the $@ variable, and the $google->{results}->{reason} hash, and parse the returned page (see the 'content' and 'header' variables.)
=back
=head2 Methods to Create/Retrieve/Delete
=head3 'Hosted account' methods
CreateAccountEmail( $userName, $firstName, $lastName, $password, $quota )
=over
Creates a hosted account with email services in your domains name space.
The first 4 arguments are required. The $quota argument is optional. If $quota is given, the tag will be sent with the request, otherwize is will be omitted.
See the Google API docs for the API call for more details.
=back
CreateAccount( $userName, $firstName, $lastName, $password )
=over
Creates a hosted account in your domains name space. This account does NOT have email services by default.
You need to call UpdateAccountEmail() to add email services.
NOTE: this API call may be discontinued! See CreateAccountEmail() for a replacement.
=back
UpdateAccount( $username, $firstName, $lastName, $password )
=over
$username is the mandatory name of the hosted account. The remaining paramaters are optional, and can be set to 'undef' if you do not wish to change them
Eg. to change the password on an account, call this as;
=back
UpdateAccount( $username, undef, undef, 'newpassword' );
=over
to change names only, you would call it as such:
=back
UpdateAccount( $username, 'newfirstname', 'newlastname', undef );
UpdateAccountEmail( $userName )
=over
Adds email services to a hosted account created with CreateAccount().
NOTE: this API call may be discontinued! See CreateAccountEmail() for a replacement.
=back
UpdateAccountStatus( $userName, $status )
=over
$status is either 'locked' or 'unlocked'
=back
RetrieveAccount( $userName )
DeleteAccount( $userName )
RenameAccount( $oldName, $newName, $alias )
=over
$alias is either '1' or '0'
WARNING: this method is derived from the Python sample code provided by Google:
(Ie. this may not work yet)
"Username change. Note that this feature must be explicitly enabled by the domain administrator, and is not enabled by default.
Args:
=over
oldname: user to rename
newname: new username to set for the user
alias: if 1, create an alias of oldname for newname"
=back
=back
=head3 'Alias' methods
CreateAlias( $userName, $alias )
RetrieveAlias( $userName );
DeleteAlias( $alias );
=head3 'Mailing List' methods
CreateMailingList( $mailingListName )
UpdateMailingList( $mailingListName, $userName, $listOperation )
=over
$listOperation is either 'add' or 'remove'
=back
RetrieveMailingList( $mailingListName )
DeleteMailingList( $mailingListName )
=head2 Methods to set/get variables
After creating the object you can get/set the administrator account and set the password with these methods.
Note this will cause a re-authentication next time a Google API method is called.
admin( $admin )
=over
set the administrative user, and will return administator username.
=back
password( $string )
=over
set the password, returns an empty string
=back
=head2 Miscelleaneous statistics methods
There are a few methods to access some statistics data that is collected while the object performing Google API calls.
authtime()
=over
returns the time of last authentication, as generated by the time() function
=back
ctime()
=over
returns the create time of the object, as generated by the time() function
=back
rtime()
=over
returns the time of the most recent request, as generated by the time() function
=back
logins()
=over
returns the number of API logins that have been performed
=back
requests()
=over
returns the numbers of API requests that have been submitted to Google
=back
success()
=over
returns the numbers of successful api request performed
=back
And finally,
version()
=over
returns a string with the api version implemented. This is currently '1.0'
=back
=head1 ACCESSING RESULTING DATA
Valid return data from Google is parsed into a hash named 'result', available through the object. In this hash you can find all elements as returned by Google.
This hash is produced by XML::Simple. See the Google API documentation in the SEE ALSO section for complete details.
Some of the more useful elements you may need to look at are:
$google->{result}->{reason} #this typically has the textual reason for a failure
$google->{result}->{extendedMessage} #a more extensive description of the failure reason may be here
$google->{result}->{result} #typically empty!
$google->{result}->{type} #should be same of query type, eg 'Account', 'Alias', 'MailingList'
The retrieval section contains data when you are querying. Here is what this section looks like when you call the RetrieveAccount method:
$google->{result}->{RetrievalSection}->{firstName}
$google->{result}->{RetrievalSection}->{lastName}
$google->{result}->{RetrievalSection}->{accountStatus}
$google->{result}->{RetrievalSection}->{aliases}->{alias}
$google->{result}->{RetrievalSection}->{emailLists}->{emailList}
To see the structure of the result hash, use the Data::Dumper module as such:
use Data::Dumper;
print Dumper($google->{result});
=head1 ACCESSING RAW GOOGLE POST AND RESULT DATA
The data from the most recent post to the Google servers is available. You can access it as:
print $google->requestcontent();
The most recent received HTML data is stored in two parts, the headers and the content. Both are strings. They can be accessed as such:
print $google->replyheaders();
print $google->replycontent();
Note the headers are new-line separated and can easily be parsed:
foreach my $headerline ( split/\n/, $g->replyheaders() )
{
my ($header, $value) = split/:/, $headerline;
}
=head1 EXPORT
None by default.
=head1 SEE ALSO
The official Google documentation can be found at
http://code.google.com/apis/apps-for-your-domain/google_apps_provisioning_api_v1.0_reference.html
For support, see the Google Group at
http://groups.google.com/group/apps-for-your-domain-apis
For additional support specific to this modules, email me at johan at reinalda dot net.
=head1 AUTHOR
Johan Reinalda, johan at reinalda dot net
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2006 by Johan Reinalda, johan at reinalda dot net
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
If you make useful modification, kindly consider emailing then to me for inclusion in a future version of this module.
=cut
VUser-Google-Api-1.0.1/lib/VUser/Google/ProvisioningAPI/V2_0.pm 0000644 0001750 0001750 00000117312 11570726507 023531 0 ustar rbsmith rbsmith package VUser::Google::ProvisioningAPI::V2_0;
use 5.008005;
use warnings;
use strict;
#(C) 2007 Randy Smith, perlstalker at vuser dot org
#(C) 2006 Johan Reinalda, johan at reinalda dot net
use vars qw($VERSION);
our $VERSION = '0.25';
use Carp;
use LWP::UserAgent qw(:strict);
use HTTP::Request qw(:strict);
use Encode;
use XML::Simple;
use Data::Dumper;
use base qw(VUser::Google::ProvisioningAPI);
use VUser::Google::ProvisioningAPI::V2_0::EmailListEntry;
use VUser::Google::ProvisioningAPI::V2_0::EmailListRecipientEntry;
use VUser::Google::ProvisioningAPI::V2_0::NicknameEntry;
use VUser::Google::ProvisioningAPI::V2_0::UserEntry;
our $APIVersion = '2.0';
#some constants
#web agent identification
use constant GOOGLEAGENT => "Google_ProvisioningAPI-perl/0.20";
#url for Google API token login
use constant GOOGLEHOST => 'www.google.com';
use constant GOOGLETOKENURL => 'https://www.google.com/accounts/ClientLogin';
use constant MAXTOKENAGE => 24 * 60 * 60; #24 hours, see API docs
#base url to the Google REST API
use constant GOOGLEBASEURL => 'https://www.google.com/a/feeds/';
use constant GOOGLEAPPSSCHEMA => 'http://schemas.google.com/apps/2006';
use constant SUCCESSCODE => 'Success(2000)';
use constant FAILURECODE => 'Failure(2001)';
#some size constants
use constant MAXNAMELEN => 40;
use constant MAXUSERNAMELEN => 30;
sub DESTROY { };
# Preloaded methods go here.
=pod
=head1 NAME
VUser::Google::ProvisioningAPI::V2_0 - Perl module that implements version 2.0 of the Google Apps for Your Domain Provisioning API
=head1 SYNOPSIS
use VUser::Google::ProvisioningAPI;
my $google = new VUser::Google::ProvisioningAPI($domain, $admin, $passwd, '2.0');
$google->CreateUser($userName, $givenName, $familyName, $password, $quotaMB);
my $user = $google->RetrieveUser($userName);
=head1 REQUIREMENTS
VUser::Google::ProvisioningAPI requires the following modules to be installed:
=over
=item
C
=item
C
=item
C
=item
C
=back
=head1 DESCRIPTION
VUser::Google::ProvisioningAPI provides a simple interface to the Google Apps for Your Domain Provisioning API.
It uses the C module for the HTTP transport, and the C module for the HTTP request and response.
=head2 Examples
Adding a user:
use VUser::Google::ProvisioningAPI;
my $google = VUser::Google::ProvisioningAPI->new('yourdomain.com',
'admin',
'your password',
'2.0');
my $entry = $google->CreateUser('joeb', 'Joe', 'Blow', 'joespassword');
if (defined $entry) {
print $entry->User, " created\n";
} else {
die "Add failed: ".$google->{result}{reason};
}
Updating a user:
my $new_entry = VUser::Google::ProvisioningAPI::V2_0::UserEntry->new();
$new_entry->Password('heresmynewpassword');
$new_entry->GivenName('Joseph');
my $entry = $google->UpdateUser('joeb', $new_entry);
Delete a user:
my $rc = $google->DeleteUser('joeb');
if (not $rc) {
die "Can't delete user: ".$google->{result}{reason};
}
=head1 CONSTRUCTOR
new ($domain, $admin, $adminpasswd)
This is the constructor for a new VUser::Google::ProvisioningAPI object.
$domain is the domain name registered with Google Apps For Your Domain,
$admin is an account in the above domain that has the right to manage that domain, and
$adminpassword is the password for that account.
Note that the constructor will NOT attempt to perform the 'ClientLogin' call to the Google Provisioning API (see below).
Authentication happens automatically when the first API call is performed. The token will be remembered for the duration of the object, and will be automatically refreshed as needed.
If you want to verify that you can get a valid token before performing any operations, follow the constructor with a call to IsAuthenticated() as such:
print "Authentication OK\n" unless not $google->IsAuthenticated();
=cut
sub new
{
#parse parameters, if any
(@_ == 4) || croak 'Constructor takes 3 arguments: domain, admin, adminpassword';
my $object = shift();
my $class = ref($object) || $object;
my $self = {
#Google related variables
domain => shift(), #the Google hosted domain we are accessing
admin => shift(), #the account to use when authenticating
password => shift(), #the password to use when authenticating
refreshtoken => 0, #if set, will force a re-authentication
authtoken => '', #the authentication token returned from google
authtime => 0, #time when authentication happened; only valid for 24 hours
requestcontent => '', #the last http content posted to Google
replyheaders => '', #the http headers of the last reply
replycontent => '', #the http content of the last reply
result => {}, #the resulting hash from the last reply data as parsed by XML::Simple
#some other variables
debug => 0, #when turned on, will spit out debug info to STDERR
#some statistics that are 'read-only'
stats => {
ctime => time, #object creation time
rtime => 0, #time of last request
requests => 0, #number of API requests made
success => 0, #number of successes
logins => 0, #number of authentications performed
}
};
#return object
bless( $self, 'VUser::Google::ProvisioningAPI::V2_0');
return $self;
}
=pod
=head1 METHODS
Below are all the methods available on the object. For the Google API specific methods, see the Google API documentation for more details.
When a request is properly handed by Google's API engine, the results of the
action are returned as the content of the request.
If the request fails (as determined by the C method
is_success()), it could mean a couple of things. If it's a failure within
the Google API, the content will contain an XML encoded error message. All
other HTTP errors are still possible.
=head2 Checking Authentication
IsAuthenticated()
=over
will check if the object has been able to authenticate with Google's api engine, and get an authentication ticket.
Returns 1 if successful, 0 on failure. To see why it may fail, see the $@ variable, and the $google->{results}->{reason} hash, and parse the returned page (see the 'content' and 'header' variables.)
=back
=cut
#check if we are authenticated. If not, try to re-login
sub IsAuthenticated {
#get object reference
my $self = shift();
if( $self->{refreshtoken} or ( (time - $self->{authtime}) > MAXTOKENAGE ) ) {
return $self->Relogin();
}
#we are still okay!
return 1;
}
=pod
Relogin()
=over
Performs a login if required. Relogin() will be called but the API methods
and IsAuthenticated(). You should not need to call this directly.
=back
=cut
#method used to (re)login to the API, either first time, or as token times out
sub Relogin
{
#get object reference
my $self = shift();
$self->dprint("Relogin called\n");
my $retval = 0;
#adjust stats counter
$self->{stats}->{logins}++;
#clear last results
$self->{replyheaders} = $self->{replycontent} = '';
$self->{result} = {};
# Create an LWP object to make the HTTP POST request
my $lwp = LWP::UserAgent->new;
if(defined($lwp)) {
$lwp->agent(GOOGLEAGENT);
$lwp->from($self->{admin}.'@'.$self->{domain});
# Submit the request with values for
# accountType, Email and Passwd variables.
my $response = $lwp->post( GOOGLETOKENURL,
[ 'accountType' => 'HOSTED',
'Email' => $self->{admin}.'@'.$self->{domain},
'Passwd' => $self->{password},
'service' => 'apps'
]
);
#save reply page
$self->{replyheaders} = $response->headers->as_string;
$self->{replycontent} = $response->content;
if ($response->is_success) {
# Extract the authentication token from the response
foreach my $line (split/\n/, $response->content) {
#$self->dprint( "RECV'd: $line" );
if ($line =~ m/^Auth=(.+)$/) {
$self->{authtoken} = $1;
$self->{authtime} = time;
$self->dprint("Token found: $self->{authtoken}\n");
#clear refresh
$self->{refreshtoken} = 0;
$retval = 1;
last;
}
}
}
else {
$self->dprint("Error in login: " . $response->status_line . "\n");
$self->{result}->{reason} = "Error in login: " . $response->status_line;
}
} else {
$self->dprint("Error getting lwp object: $!\n");
$self->{result}->{reason} = "Error getting lwp object: $!";
}
return $retval;
}
#generic request routine that handles most functionality
#requires 3 arguments: Method, URL, Body
#Method is the HTTP method to use. ('GET', 'POST', etc)
#URL is the API URL to talk to.
#Body is the xml specific to the action.
# This is not used on 'GET' or 'DELETE' requests.
sub Request
{
my $retval = 0;
#get object reference
my $self = shift();
$self->dprint( "***REQUEST***\n");
#clear last results
$self->{replyheaders} = $self->{replycontent} = '';
$self->{result} = {};
if(@_ != 2 and @_ != 3) {
$self->{result}->{reason} = 'Invalid number of arguments to request()';
return 0;
}
#get parameters
my($method,$url,$body) = @_;
#$self->dprint( "Type: $type\nAction: $action\n$body\n");
$self->dprint("Method: $method; URL: $url\n");
$self->dprint("Body: $body\n") if $body;
#keep some stats
$self->{stats}->{requests}++;
$self->{stats}->{rtime} = time;
#check if we are authenticated to google
if(!$self->IsAuthenticated()) {
$self->dprint( "Error authenticating\n");
return 0;
}
#standard XML pre and post segments
# TODO: this changes in 2.0
#properly encode it
$body = encode('UTF-8',$body);
#save the request content
$self->{requestcontent} = $body;
# Create an LWP object to make the HTTP POST request over
my($ua) = LWP::UserAgent->new;
if(!defined($ua)) {
$self->dprint("Cannot create LWP::UserAgent object: $!\n");
$self->{result}->{reason} = "Cannot create LWP::UserAgent object in request(): $!";
return $retval;
}
#and create the request object where are we connecting to
# v2.0 uses a diffent url based what's being done.
# The API methods will construct the URL becuase action specific
# information, such as domain and user, is embedded with it.
# v2.0 use different methods depending on the action
# It's up to the API methods to know which method to use
my $req = HTTP::Request->new($method => $url);
if(!defined($req)) {
$self->dprint("Cannot create HTTP::Request object: $!\n");
$self->{result}->{reason} = "Cannot create HTTP::Request object in request(): $!";
return $retval;
}
#set some user agent variables
$ua->agent( GOOGLEAGENT );
$ua->from( '<' . $self->{admin}.'@'.$self->{domain} . '>');
# Submit the request
$req->header('Accept' => 'application/atom+xml');
$req->header('Content-Type' => 'application/atom+xml');
if ($body) {
$req->header('Content-Length' => length($body) );
}
$req->header('Connection' => 'Keep-Alive');
$req->header('Host' => GOOGLEHOST);
$req->header('Authorization' => 'GoogleLogin auth='.$self->{authtoken});
#assign the data to the request
# Perhaps if $method eq 'GET' or 'DELETE' would be better
if ($body) {
$req->content($body);
}
#$self->dprint(Data::Dumper::Dumper($req));
#execute the request
my $response = $ua->request($req);
$self->dprint(Data::Dumper::Dumper($response));
#save reply page
$self->{replyheaders} = $response->headers->as_string;
$self->{replycontent} = $response->content;
#check result
if ($response->is_success) {
$self->{stats}->{success}++;
$self->dprint( "Success in post:\n");
#delete all namespace elements to keep it simple (ie. remove "hs:")
#this avoids the need to use XML::NameSpace
# v2.0 uses a couple namespaces now, instead of just one.
# I'm not sure that we can avoid using XML::NameSpace
my $xml = decode('UTF-8', $response->content);
#$xml =~ s/hs\://g;
$self->dprint( $xml );
if ($xml) {
#now go parse it using XML::Simple
my $simple = XML::Simple->new(ForceArray => 1);
#my $parser = XML::SAX::ParserFactory->new(Handler => $simple);
#$self->{result} = $parser->parse_string($xml);
$self->{result} = $simple->XMLin($xml);
# (OLD) $self->{result} = XMLin($xml,ForceArray => 0);
#include Data::Dumper above if you want to use this line:
$self->dprint( Dumper($self->{result}) );
} else {
$self->{result} = {};
}
$self->dprint("Google API success!");
$retval = 1;
}
else {
# OK. Funky issue. When trying to get a user that doesn't exist,
# Google throws a 400 error instead of returning a error document.
# Google has fun. If there is a problem with the request,
# google triggers a 400 error witch then fails on ->is_success.
# So, we need to check the content anyway to see if there is a
# reason for the failure.
$self->dprint("Google API failure!");
my $xml = decode('UTF-8', $response->content);
$self->dprint( $xml );
if ($xml) {
my $simple = XML::Simple->new(ForceArray => 1);
$self->{result} = $simple->XMLin($xml);
$self->dprint( 'Error result: '.Dumper($self->{result}) );
}
if (defined ($self->{result}{error}[0]{reason})) {
$@ = "Google API failure: "
.$self->{result}{error}[0]{errorCode}.' - '
.$self->{result}{error}[0]{reason};
$self->dprint("$@\n");
$self->{result}->{reason} = $@;
} else {
$@ = "Google API failure: reason not found!";
$self->dprint( "Error in post: " . $response->status_line . "\n");
$self->{result}->{reason} = "Error in http post: " . $response->status_line;
}
}
#show full response for now
#$self->dprint( "Headers:\n" . $response->headers->as_string);
#foreach my $line (split/\n/, $response->content) {
# $self->dprint( "RECV'd: $line\n");
#}
return $retval;
}
=pod
=head2 User Methods
These are the acutual API calls. These calls match up with the client
library methods described for the .Net and Java libraries.
=cut
### HOSTED ACCOUNT routines ###
=pod
CreateUser($userName, $givenName, $familyName, $password, $quota, $forceChange, $hashName)
=over
Creates a user in your Google Apps domain. The first four arguments are
required. The C<$quota> argument is optional and may not do anything unless
your agreement with Google allows you to change quotas.
If C<$forceChange> is true, the user will be required to change their
password after log in.
C<$hashName>, if set, must be I or I.
CreateUser() returns a C object if
the request was successful and C otherwise.
=back
=cut
sub CreateUser {
my $self = shift;
if (@_ < 4 and @_ > 7) {
$self->dprint("CreateUser method requires 4 to 7 arguments\n");
$self->{result}->{reason} = "CreateUser method requires 4 to 7 arguments";
return undef;
}
my ($username, $given_name, $family_name, $password, $quotaMB, $forceChange, $hash_name) = @_;
$forceChange = $forceChange? 1 : 0;
if(defined $hash_name) {
if(lc($hash_name) eq "sha-1") {
$hash_name = "SHA-1";
} elsif (lc($hash_name) eq 'md5') {
$hash_name = "MD5";
}
else {
# Unset $hash_name if it's not a valid hash type
$hash_name = undef;
}
}
my $body = $self->XMLPrefix;
#LP:changePasswordAtNextLogin (todo)
$body .= '';
$body .= "" if defined $quotaMB;
$body .= "";
$body .= $self->XMLPostfix;
if ($self->Request('POST',
GOOGLEBASEURL.$self->{domain}."/user/$APIVersion",
$body)) {
my $entry = $self->buildUserEntry();
return $entry;
} else {
return undef;
}
# Return UserEntry
}
=pod
RetrieveUser($userName)
=over
Get the passed user from Google. Returns a
C object.
=back
=cut
sub RetrieveUser {
my $self = shift;
if (@_ != 1) {
$self->dprint("RetrieveUser method requires 1 argument\n");
$self->{result}->{reason} = "RetrieveUser method requires 1 argument";
return undef;
}
my $username = shift;
my $url = GOOGLEBASEURL.$self->{domain}."/user/$APIVersion/$username";
if ($self->Request('GET',$url)) {
return $self->buildUserEntry();
} else {
return undef;
}
# Return UserEntry
}
=pod
RetrieveAllUsers()
=over
Returns a list of all users in your domain. The entries are
C objects.
=back
=cut
sub RetrieveAllUsers {
my $self = shift;
# Need to deal with google's pagination thing.
my $last_page = 0;
my $url = GOOGLEBASEURL.$self->{domain}."/user/$APIVersion";
my @entries = ();
while (not $last_page) {
# It might be better to adjust this to use RetrievePageOfUsers()
if ($self->Request('GET', $url)) {
foreach my $entry (@{ $self->{result}{'entry'} }) {
push @entries, $self->buildUserEntry($entry);
}
} else {
# There was some sort of error which caused the lookup to fail.
# This also means that if pages beyond the first fail, the entire
# dataset is discarded.
return undef;
}
$last_page = 1; # gets reset to 0 if there are more pages
# Look through the links to see if there's another page.
# A link with rel=next means that we have another page to look at.
#
# TODO: May be more efficient with a last; in the else but
# I had problems with infinite loops while trying to get it
# sorted out.
foreach my $link (@{ $self->{result}{'link'} }) {
if ($link->{'rel'} eq 'next') {
$url = $link->{'href'};
$last_page = 0;
# } else {
# $last_page = 1;
}
}
}
return @entries;
# Return list of UserEntries
}
=pod
RetrievePageOfUsers($startUser)
=over
Google Provisioning API 2.0 supports returning lists of users 100 at a time.
C<$startUser> is optional. When used, it will be the list will start at
that user. Otherwise, it will return the first 100 users.
RetrievePageOfUsers() returns a list of
C objects.
=back
=cut
sub RetrievePageOfUsers {
my $self = shift;
if (@_ > 1) {
$self->dprint("RetrievePageOfUser method requires 0 or 1 argument\n");
$self->{result}->{reason} = "RetrievePageOfUser method requires 0 or 1 argument";
return undef;
}
my $start_username = shift;
my $url = GOOGLEBASEURL.$self->{domain}."/user/$APIVersion";
$url .= "?startUsername=$start_username" if defined $start_username;
my @entries = ();
if ($self->Request('GET', $url)) {
foreach my $entry (@{ $self->{result}{'entry'} }) {
push @entries, $self->buildUserEntry($entry);
}
} else {
# There was some sort of error which caused the lookup to fail.
# This also means that if pages beyond the first fail, the entire
# dataset is discarded.
return undef;
}
# Return list of UserEntries
return @entries;
}
=pod
UpdateUser($userName, $newUserEntry)
=over
C<$userName> is the mandatory name of the user account. C<$newUserEntry> is a
C object with the changes to the
account. You only need to set the elements of C<$newUserEntry> that are being
changed. B According to the Google API docs, you should not set the
password unless you are actually changing the password.
=back
=cut
sub UpdateUser {
my $self = shift;
if (@_ != 2) {
$self->dprint("UpdateUser method requires 2 arguments\n");
$self->{result}->{reason} = "UpdateUser method requires 2 arguments";
return undef;
}
my $username = shift;
my $new_entry = shift; # G::P::V2_0::UserEntry
my $body = $self->XMLPrefix;
$body .= '';
if (defined ($new_entry->User)
or defined ($new_entry->Password)
or defined ($new_entry->isSuspended)
or defined ($new_entry->changePasswordAtNextLogin)
) {
$body .= '{hashFunctionName}) {
$body .= ' hashFunctionName="'.$new_entry->{hashFunctionName}.'"';
}
$body .= ' userName="'.$new_entry->User.'"' if defined $new_entry->User;
if (defined $new_entry->Password) {
my $passwd = $new_entry->Password;
# escape quotes
# See section 2.4 of http://www.w3.org/TR/xml/
#$passwd =~ s/\"/\\"/;
$passwd =~ s/\"/"/;
$body .= ' password="'.$passwd.'"';
}
$body .= ' suspended="'.($new_entry->isSuspended? 'true' : 'false').'"';
#LP:changePasswordAtNextLogin
#print "too(".$new_entry->changePasswordAtNextLogin.")";
$body .= ' changePasswordAtNextLogin="'.($new_entry->changePasswordAtNextLogin? 'true' : 'false').'"';
$body .= '/>';
}
if (defined ($new_entry->FamilyName)
or defined ($new_entry->GivenName)) {
$body .= 'FamilyName.'"' if defined $new_entry->FamilyName;
$body .= ' givenName="'.$new_entry->GivenName.'"' if defined $new_entry->GivenName;
$body .= '/>';
}
if (defined ($new_entry->Quota)) {
$body .= '';
}
$body .= $self->XMLPostfix;
# The body has been contructed. We are 'Go' to make the request.
if ($self->Request('PUT',
GOOGLEBASEURL.$self->{domain}."/user/$APIVersion/$username",
$body)) {
my $entry = $self->buildUserEntry();
return $entry;
} else {
return undef;
}
# Return UserEntry
}
=pod
SuspendUser($userName)
=over
C<$userName> is the name of the user that you want to suspend.
Returns a C object if successful.
=back
=cut
sub SuspendUser {
my $self = shift;
my $username = shift;
my $entry = VUser::Google::ProvisioningAPI::V2_0::UserEntry->new();
$entry->isSuspended(1);
return $self->UpdateUser($username, $entry);
# Return UserEntry
}
=pod
RestoreUser($userName)
=over
Unsuspend the user's account. C<$userName> is required.
Returns a C object if successful.
=back
=cut
sub RestoreUser {
my $self = shift;
my $username = shift;
my $entry = VUser::Google::ProvisioningAPI::V2_0::UserEntry->new();
$entry->isSuspended(0);
return $self->UpdateUser($username, $entry);
# Return UserEntry
}
=pod
DeleteUser($userName)
=over
C<$userName> is the required user name to delete.
Returns '1' on success.
=back
=cut
sub DeleteUser {
my $self = shift;
if (@_ != 1) {
$self->dprint("DeleteUser method requires 1 argument\n");
$self->{result}->{reason} = "DeleteUser method requires 1 argument";
return undef;
}
my $username = shift;
if ($self->Request('DELETE',
GOOGLEBASEURL.$self->{domain}."/user/$APIVersion/$username")) {
return 1;
} else {
return undef;
}
# Return undef
}
### NICKNAME routines ###
=pod
=head3 Nickname methods
CreateNickname($userName, $nickName)
=over
Creates a nickname (or alias) for a user. C<$userName> is the existing user
and C<$nickName> is the user's new nickname.
Returns a C object on success.
=back
=cut
sub CreateNickname {
my $self = shift;
if (@_ != 2) {
$self->dprint("CreateNickname method requires 2 arguments\n");
$self->{result}->{reason} = "CreateNickname method requires 2 arguments";
return undef;
}
my $username = shift;
my $nickname = shift;
my $body = $self->XMLPrefix;
$body .= '';
$body .= "";
$body .= "";
$body .= $self->XMLPostfix;
if ($self->Request('POST',
GOOGLEBASEURL.$self->{domain}."/nickname/$APIVersion",
$body)) {
return $self->buildNicknameEntry();
} else {
return undef;
}
# Return NicknameEntry
}
=pod
RetrieveNickname($nickName)
=over
Returns a C if the C<$nickName>
exists.
=back
=cut
sub RetrieveNickname {
my $self = shift;
if (@_ != 1) {
$self->dprint("RetrieveNickname method requires 1 argument\n");
$self->{result}->{reason} = "RetrieveNickname method requires 1 argument";
return undef;
}
my $nickname = shift;
if ($self->Request('GET',
GOOGLEBASEURL.$self->{domain}."/nickname/$APIVersion/$nickname")) {
return $self->buildNicknameEntry();
} else {
return undef;
}
# Return NicknameEntry
}
=pod
RetrieveNicknames($userName)
=over
Get all nicknames for C<$userName>.
Returns a list of C objects.
=back
=cut
sub RetrieveNicknames {
my $self = shift;
if (@_ != 1) {
$self->dprint("RetrieveNicknames method requires 1 argument\n");
$self->{result}->{reason} = "RetrieveNicknames method requires 1 argument";
return undef;
}
my $username = shift;
my $url = GOOGLEBASEURL.$self->{domain}."/nickname/$APIVersion?username=$username";
my $last_page = 0;
my @entries = ();
# And we get to deal with funky pagination here, too.
while (not $last_page) {
if ($self->Request('GET', $url)) {
foreach my $entry (@{ $self->{result}{'entry'} }) {
push @entries, $self->buildNicknameEntry($entry);
}
} else {
return undef;
}
# Look through the links to see if there's another page.
# A link with rel=next means that we have another page to look at.
foreach my $link (@{ $self->{result}{'link'} }) {
if ($link->{'rel'} eq 'next') {
$url = $link->{'href'};
$last_page = 0;
} else {
$last_page = 1;
}
}
}
return @entries;
# Return list of NicknameEntries
}
=pod
RetrieveAllNicknames()
=over
Get all of the nick names for your domain.
Returns a list of C objects.
=back
=cut
sub RetrieveAllNicknames {
my $self = shift;
my $url = GOOGLEBASEURL.$self->{domain}."/nickname/$APIVersion";
my $last_page = 0;
my @entries = ();
# And we get to deal with funky pagination here, too.
while (not $last_page) {
if ($self->Request('GET', $url)) {
foreach my $entry (@{ $self->{result}{'entry'} }) {
push @entries, $self->buildNicknameEntry($entry);
}
} else {
return undef;
}
# Look through the links to see if there's another page.
# A link with rel=next means that we have another page to look at.
foreach my $link (@{ $self->{result}{'link'} }) {
if ($link->{'rel'} eq 'next') {
$url = $link->{'href'};
$last_page = 0;
} else {
$last_page = 1;
}
}
}
return @entries;
# Return list of NicknameEntries
}
=pod
RetrievePageOfNicknames($startNick)
=over
Get 100 of the nick names for your domain. If C<$startNick> is defined,
the list will start with that nick name, otherwise, the first 100 nicks
will be returned.
Returns a list of C objects.
=back
=cut
sub RetrievePageOfNicknames {
my $self = shift;
my $start_nick = shift;
my $url = GOOGLEBASEURL.$self->{domain}."/nickname/$APIVersion";
$url .= "?startNickname=$start_nick" if defined $start_nick;
my @entries = ();
if ($self->Request('GET', $url)) {
foreach my $entry (@{ $self->{result}{'entry'} }) {
push @entries, $self->buildNicknameEntry($entry);
}
} else {
return undef;
}
return @entries;
# Return list of NicknameEntries
}
=pod
DeleteNickname($nickName)
=over
Delete C<$nickName> from your domain. Returns 1 if the request succeeds.
=back
=cut
sub DeleteNickname {
my $self = shift;
if (@_ != 1) {
$self->dprint("DeleteNickname method requires 1 argument\n");
$self->{result}->{reason} = "DeleteNickname method requires 1 argument";
return undef;
}
my $nickname = shift;
if ($self->Request('DELETE',
GOOGLEBASEURL.$self->{domain}."/nickname/$APIVersion/$nickname")) {
return 1;
} else {
return undef;
}
# Return undef
}
### EMAIL LIST routines ###
=pod
=head3 Email list methods
CreateEmailList($listName)
=over
Create an email list named C<$listName>.
Returns a C on success.
=back
=cut
sub CreateEmailList {
my $self = shift;
if (@_ != 1) {
$self->dprint("CreateEmailList method requires 1 argument\n");
$self->{result}->{reason} = "CreateEmailList method requires 1 argument";
return undef;
}
my $emaillist = shift;
my $body = $self->XMLPrefix;
$body .= '';
$body .= "";
$body .= $self->XMLPostfix;
if ($self->Request('POST',
GOOGLEBASEURL.$self->{domain}."/emailList/$APIVersion",
$body)) {
my $entry = $self->buildEmailListEntry();
return $entry;
} else {
return undef;
}
# Return EmailListEntry
}
=pod
RetrieveEmailLists($recipient)
=over
Get a list of all local email lists that C<$recipient> is subscribed to.
C<$recipient> is limited to users at your domain.
Returns a list of C objects.
=back
=cut
sub RetrieveEmailLists {
my $self = shift;
if (@_ != 1) {
$self->dprint("RetrieveEmailLists method requires 1 argument\n");
$self->{result}->{reason} = "RetrieveEmailLists method required 1 argument\n";
}
my $recipient = shift;
my $url = GOOGLEBASEURL.$self->{domain}."/emailList/$APIVersion?recipient=$recipient";
my $last_page = 0;
my @entries = ();
# Work with Google's pagination
while (not $last_page) {
if ($self->Request('GET', $url)) {
foreach my $entry (@{ $self->{result}{'entry'} }) {
push @entries, $self->buildEmailListEntry($entry);
}
} else {
return undef;
}
# Look for next page link
foreach my $link (@{ $self->{result}{'link'} }) {
if ($link->{'rel'} eq 'next') {
$url = $link->{'href'};
$last_page = 0;
} else {
$last_page = 1;
}
}
}
# Return list of EmailListEntries
return @entries;
}
=pod
RetrieveAllEmailLists()
=over
Get a list of all email lists for your domain.
Returns a list of C objects.
=back
=cut
sub RetrieveAllEmailLists {
my $self = shift;
my $url = GOOGLEBASEURL.$self->{domain}."/emailList/$APIVersion";
my $last_page = 0;
my @entries = ();
# Work with Google's pagination
while (not $last_page) {
if ($self->Request('GET', $url)) {
foreach my $entry (@{ $self->{result}{'entry'} }) {
push @entries, $self->buildEmailListEntry($entry);
}
} else {
return undef;
}
# Look for next page link
foreach my $link (@{ $self->{result}{'link'} }) {
if ($link->{'rel'} eq 'next') {
$url = $link->{'href'};
$last_page = 0;
} else {
$last_page = 1;
}
}
}
# Return list of EmailListEntries
return @entries;
}
=pod
RetrievePageOfEmailLists($startList)
=over
Get a single page (100 lists) of email lists.
=back
=cut
sub RetrievePageOfEmailLists {
my $self = shift;
my $start_emaillist = shift;
my $url = GOOGLEBASEURL.$self->{domain}."/emailList/$APIVersion";
if ($start_emaillist) {
$url .= "?startEmailListName=$start_emaillist";
}
my @entries = ();
if ($self->Request('GET', $url)) {
foreach my $entry (@{ $self->{result}{'entry'} }) {
push @entries, $self->buildEmailListEntry($entry);
}
} else {
return undef;
}
# Return list of EmailListEntries
return @entries;
}
=pod
DeleteEmailList($emailList)
=over
Delete C<$emailList> from your domain.
Returns 1 on success.
=back
=cut
sub DeleteEmailList {
my $self = shift;
if (@_ != 1) {
$self->dprint("DeleteUser method requires 1 argument\n");
$self->{result}->{reason} = "DeleteUser method requires 1 argument";
return undef;
}
my $emaillist = shift;
if ($self->Request('DELETE',
GOOGLEBASEURL.$self->{domain}."/emailList/$APIVersion/$emaillist")) {
return 1;
} else {
return undef;
}
# Return undef
}
=pod
AddRecipientToEmailList($recipient, $emailList)
=over
Adds a recipient to a mail list. C<$recipient> is the address you want to
add and C<$emailList> is the list to add to.
Returns a C object on
success.
=back
=cut
sub AddRecipientToEmailList {
my $self = shift;
if (@_ != 2) {
$self->dprint("AddRecipientToEmailList method requires 2 argument\n");
$self->{result}->{reason} = "AddRecipientToEmailList method requires 2 argument";
return undef;
}
my $recipient = shift;
my $emaillist = shift;
my $body = $self->XMLPrefix;
$body =~ s!>$! xmlns:gd="http://schemas.google.com/g/2005">!;
$body .= '';
$body .= "";
$body .= $self->XMLPostfix;
if ($self->Request('POST',
GOOGLEBASEURL.$self->{domain}
."/emailList/$APIVersion/$emaillist/recipient",
$body)) {
my $entry = $self->buildEmailListRecipientEntry();
return $entry;
} else {
return undef;
}
# Return EmailListRecipientEntry
}
=pod
RetrieveAllRecipients($emailList)
=over
Get a list of the recipients of the specified email list.
Returns a list of C objects.
=back
=cut
sub RetrieveAllRecipients {
my $self = shift;
if (@_ != 1) {
$self->dprint("RetrieceAllRecipients method requires 1 argument\n");
$self->{result}->{reason} = "RetrieveAllRecipients method requires 1 argument";
return undef;
}
my $emaillist = shift;
my $url = GOOGLEBASEURL.$self->{domain}."/emailList/$APIVersion/$emaillist/recipient";
my $last_page = 0;
my @entries = ();
# Google Pagination again
while (not $last_page) {
if ($self->Request('GET', $url)) {
foreach my $entry (@{ $self->{result}{'entry'} }) {
my $entry = $self->buildEmailListRecipientEntry($entry);
push @entries, $entry if $entry;
}
} else {
return undef;
}
foreach my $link (@{ $self->{result}{'link'} }) {
if ($link->{'rel'} eq 'next') {
$url = $link->{'href'};
$last_page = 0;
} else {
$last_page = 1;
}
}
}
# Return list of EmailListRecipientEntries
return @entries;
}
=pod
RetrievePageOfRecipients($emailList, $startRecpt)
=over
Get a page of recipients for that given list (C<$emailList)> starting with
C<$startRecpt> or the beginning if C<$startRecpt> is not defined.
Returns a list of C objects.
=back
=cut
sub RetrievePageOfRecipients {
my $self = shift;
if (@_ != 2) {
$self->dprint("RetrievePageOfRecipients method requires 2 arguments\n");
$self->{result}->{reason} = "RetrievePageOfRecipients method requires 2 arguments";
return undef;
}
my $emaillist = shift;
my $start_rcpt = shift;
my $url = GOOGLEBASEURL.$self->{domain}."/emailList/$APIVersion/$emaillist/recipient";
if ($start_rcpt) {
$url .= "?startRecipient=$start_rcpt";
}
my @entries = ();
if ($self->Request('GET', $url)) {
foreach my $entry (@{ $self->{result}{'entry'} }) {
push @entries, $self->buildEmailListRecipientEntry();
}
} else {
return undef;
}
# Return list of EmailListRecipientEntries
return @entries;
}
=pod
RemoveRecipientFromEmailList($recipient, $emailList)
=over
Remove C<$recipient> from the given email list (C<$emailList>).
Returns 1 in success.
=back
=cut
sub RemoveRecipientFromEmailList {
my $self = shift;
if (@_ != 2) {
$self->dprint("RemoveRecipientFromEmailList method requires 2 arguments\n");
$self->{result}->{reason} = "RemoveRecipientFromEmailList method requires 2 arguments";
return undef;
}
my $recipient = shift;
my $emaillist = shift;
if ($self->Request('DELETE',
GOOGLEBASEURL.$self->{domain}
."/emailList/$APIVersion/$emaillist/recipient/$recipient")) {
return 1;
} else {
return undef;
}
# Return undef
}
### Private methods
sub XMLPrefix {
my $pre = '';
$pre .= '';
return $pre;
}
sub XMLPostfix {
return '';
}
sub buildUserEntry {
my $self = shift;
my $xml = shift || $self->{result};
my $entry = VUser::Google::ProvisioningAPI::V2_0::UserEntry->new();
$entry->User($xml->{'apps:login'}[0]{'userName'});
if ($xml->{'apps:login'}[0]{'suspended'}) {
if ($xml->{'apps:login'}[0]{'suspended'} eq 'true') {
$entry->isSuspended(1);
} else {
$entry->isSuspended(0);
}
}
#LP: changePasswordAtNextLogin
if ($xml->{'apps:login'}[0]{'changePasswordAtNextLogin'}) {
if ($xml->{'apps:login'}[0]{'changePasswordAtNextLogin'} eq 'true') {
$entry->changePasswordAtNextLogin(1);
} else {
$entry->changePasswordAtNextLogin(0);
}
}
$entry->FamilyName($xml->{'apps:name'}[0]{'familyName'});
$entry->GivenName($xml->{'apps:name'}[0]{'givenName'});
$entry->Quota($xml->{'apps:quota'}[0]{'limit'});
return $entry;
}
sub buildNicknameEntry {
my $self = shift;
my $xml = shift || $self->{result};
my $entry = VUser::Google::ProvisioningAPI::V2_0::NicknameEntry->new();
$entry->User($xml->{'apps:login'}[0]{'userName'});
# Odd parser problem:
#
# yeilds:
# 'apps:nickname' => { 'test1' => {} },
#$entry->Nickname($xml->{'apps:nickname'}[0]{'name'});
# This is an exceptionally ugly hack to work around the parser issue
# above.
$entry->Nickname((keys %{$xml->{'apps:nickname'}})[0]);
return $entry;
}
sub buildEmailListEntry {
my $self = shift;
my $xml = shift || $self->{'result'};
my $entry = VUser::Google::ProvisioningAPI::V2_0::EmailListEntry->new();
# This seems to have the same problem as nicknames.
#$entry->EmailList($xml->{'apps:emailList'}[0]{'name'});
$entry->EmailList((keys %{$xml->{'apps:emailList'}})[0]);
return $entry;
}
sub buildEmailListRecipientEntry {
my $self = shift;
my $xml = shift || $self->{'result'};
my $entry = VUser::Google::ProvisioningAPI::V2_0::EmailListRecipientEntry->new();
$entry->Who($xml->{'gd:who'}[0]{'email'});
return $entry;
}
=pod
=head1 ACCESSING RESULTING DATA
Most API calls return an object so that you don't have to screw around with the
XML data. The parsed XML (by XML::Simple) is available in C<$google->{result}>.
=head1 EXPORT
None by default.
=head1 SEE ALSO
The perldocs for VUser::Google::ProvisioningAPI::V2_0::UserEntry;
VUser::Google::ProvisioningAPI::V2_0::NicknameEntry;
VUser::Google::ProvisioningAPI::V2_0::EmailListEntry;
and VUser::Google::ProvisioningAPI::V2_0::EmailListRecipientEntry.
The official Google documentation can be found at
http://code.google.com/apis/apps-for-your-domain/google_apps_provisioning_api_v2.0_reference.html
http://code.google.com/apis/apps/gdata_provisioning_api_v2.0_reference.html
For support, see the Google Group at
http://groups.google.com/group/apps-for-your-domain-apis
For additional support specific to this modules, email me at johan at reinalda dot net.
=head1 AUTHOR
Johan Reinalda, johan at reinalda dot net
Randy Smith, perlstalker at vuser dot org
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2006 by Johan Reinalda, johan at reinalda dot net
Copyright (C) 2007 by Randy Smith, perlstalker at vuser dot org
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
If you make useful modification, kindly consider emailing then to me for inclusion in a future version of this module.
=cut
1;
VUser-Google-Api-1.0.1/lib/VUser/Google/Provisioning/ 0000755 0001750 0001750 00000000000 11570731200 022110 5 ustar rbsmith rbsmith VUser-Google-Api-1.0.1/lib/VUser/Google/Provisioning/V2_0.pm 0000644 0001750 0001750 00000044120 11570726510 023165 0 ustar rbsmith rbsmith package VUser::Google::Provisioning::V2_0;
use warnings;
use strict;
our $VERSION = '0.2.0';
use Moose;
extends 'VUser::Google::Provisioning';
use VUser::Google::Provisioning::UserEntry;
has '+base_url' => (default => 'https://apps-apis.google.com/a/feeds/');
#### Methods ####
## Users
#
# %options
# userName*
# givenName*
# familyName*
# password*
# hashFunctioName (SHA-1|MD5)
# suspended (bool)
# quota (in MB)
# changePasswordAtNextLogin (bool)
# admin (bool)
sub CreateUser {
my $self = shift;
my %options = ();
if (ref $_[0]
and $_[0]->isa('VUser::Google::Provisioning::UserEntry')) {
%options = $_[0]->as_hash;
}
else {
%options = @_;
}
$self->google()->Login();
my $url = $self->base_url.$self->google->domain.'/user/2.0';
my $post = '
';
## login
$post .= '_escape_quotes($options{'password'})."\"";
if ($options{hashFunctionName}) {
$post .= " hashFunctionName=\"$options{hashFunctionName}\"";
}
if ($options{suspended}) {
$post .= ' suspended="'.$self->_as_bool($options{suspended}).'"';
}
if ($options{changePasswordAtNextLogin}) {
$post .= ' changePasswordAtNextLogin="'
.$self->_as_bool($options{changePasswordAtNextLogin}).'"';
}
if ($options{admin}) {
$post .= ' admin="'.$self->_as_bool($options{admin}).'"';
}
$post .= '/>';
## quota
if ($options{quota}) {
$post .= "";
}
## name
$post .= 'google->Request('POST', $url, $post)) {
## build UserEntry
$self->dprint('Created user');
my $entry = $self->_build_user_entry($self->google->result);
return $entry;
}
else {
## ERROR!
$self->dprint('CreateUser failed: '.$self->google->result->{reason});
die "Error creating user: ".$self->google->result->{'reason'}."\n";
}
}
sub RetrieveUser {
my $self = shift;
my $username = shift;
my $url = $self->base_url.$self->google->domain.'/user/2.0/'.$username;
if ($self->google->Request('GET', $url)) {
return $self->_build_user_entry($self->google->result);
}
else {
if ($self->google->result->{'reason'} =~ /EntityDoesNotExist/) {
return undef;
}
else {
die "Error retrieving user: ".$self->google->result->{'reason'}."\n";
}
}
}
# Retrieve one page of users.
# How to return the next page?
# Returns (
# entries => \@entries, # list of UserEntry objects
# next => $next # the next username if another page exists
# # undef otherwise
# )
sub RetrieveUsers {
my $self = shift;
my $start_user = shift;
my @entries = ();
my $next_user;
my $url = $self->base_url.$self->google->domain.'/user/2.0';
if ($start_user) {
$url .= "?startUsername=$start_user";
}
if ($self->google->Request('GET', $url)) {
foreach my $entry (@{ $self->google->result->{'entry'} }) {
## Create UserEntry object
my $user = $self->_build_user_entry($entry);
push @entries, $user;
}
}
else {
## There was an error
die "Error fetching users: ".$self->google->result->{'reason'}."\n";
}
# Look for the a link tag that says there should be more results
# A link tag with rel=next means there is another page
foreach my $link (@{ $self->google->result->{'link'} }) {
if ($link->{'rel'} eq 'next') {
$url = $link->{'href'};
if ($url =~ /startUsername=([^\"]+)/) {
$next_user = $1;
}
}
}
return ( entries => \@entries, next => $next_user );
}
# Alias for RetrieveUsers
sub RetrievePageOfUsers {
$_[0]->RetrieveUsers(@_);
}
# Returns a list of UserEntry objects
sub RetrieveAllUsers {
my $self = shift;
my @entries = ();
my $next;
my %results;
eval {
%results = $self->RetrieveUsers;
push @entries, @{ $results{'entries'} };
$next = $results{'next'};
};
die $@ if $@;
while ($next) {
eval {
%results = $self->RetrieveUsers($next);
push @entries, @{ $results{'entries'} };
$next = $results{'next'};
};
die $@ if $@;
}
return @entries;
}
# %options
# userName*
# givenName
# familyName
# password
# hashFunctioName (SHA-1|MD5)
# suspended (bool)
# quota (in MB)
# changePasswordAtNextLogin (bool)
# admin (admin)
sub UpdateUser {
my $self = shift;
my %options = ();
if (ref $_[0]
and $_[0]->isa('VUser::Google::Provisioning::UserEntry')) {
%options = $_[0]->as_hash;
}
else {
%options = @_;
}
die "Can't update user: userName not set\n" unless $options{'userName'};
my $url = $self->base_url.$self->google->domain
."/user/2.0/$options{userName}";
my $post = '
';
## update user info (login tag)
if ($options{password}
or defined $options{suspended}
or defined $options{changePasswordAtNextLogin}
or defined $options{admin}
) {
$post .= '_escape_quotes($options{'password'});
$post .= '"';
if (defined $options{hashFunctionName}) {
$post .= ' hashFunctionName="';
$post .= $options{hashFunctionName};
$post .= '"';
}
}
if (defined $options{suspended}) {
$post .= ' suspended="'.$self->_as_bool($options{suspended}).'"';
}
if (defined $options{changePasswordAtNextLogin}) {
$post .= ' changePasswordAtNextLogin="'
.$self->_as_bool($options{changePasswordAtNextLogin}).'"';
}
if (defined $options{admin}) {
$post .= ' admin="'.$self->_as_bool($options{admin}).'"';
}
$post .= '/>';
}
## Quota
if ($options{quota}) {
$post .= "";
}
## Name
if ($options{givenName} or $options{familyName}) {
$post .= 'google->Request('PUT', $url, $post)) {
$self->dprint('Updated user');
my $entry = $self->_build_user_entry($self->google->result);
return $entry;
}
else {
die "Error updating user: ".$self->google->result->{'reason'}."\n";
}
}
sub RenameUser {
my $self = shift;
my $oldname = shift;
my $newname = shift;
die "Can't rename user: old userName not set\n" unless $oldname;
die "Can't rename user: new userName not set\n" unless $newname;
my $url = $self->base_url.$self->google->domain
."/user/2.0/$oldname";
my $user = $self->RetrieveUser($oldname)
or die "Unknown user: $oldname\n";
my $post = '
';
$post .= '$oldname';
$post .= 'base_url.
$self->google->domain."/user/2.0/$oldname\"/>";
$post .= 'base_url.
$self->google->domain."/user/2.0/$oldname\"/>";
$post .= "_as_bool($user->Suspended).'"';
$post .= ' admin="'.$self->_as_bool($user->Admin).'"';
$post .= ' changePasswordAtNextLogin="'
.$self->_as_bool($user->ChangePasswordAtNextLogin).'"';
# $post .= ' agreedToTerms="'.$self->_as_bool($user->AgreedToTerms).'"';
$post .= "/>";
$post .= '';
if ($self->google->Request('PUT', $url, $post)) {
$self->dprint("Renamed $oldname to $newname");
my $entry = $self->_build_user_entry($self->google->result);
return $entry;
}
else {
die "Error rename user: ".$self->google->result->{'reason'}."\n";
}
}
sub DeleteUser {
my $self = shift;
my $user;
if (ref $_[0] and $_[0]->isa('VUser::Google::Provisioning::UserEntry')) {
$user = $_[0]->UserName
}
else {
$user = $_[0];
}
my $url = $self->base_url.$self->google->domain.'/user/2.0/'.$user;
if ($self->google->Request('DELETE', $url)) {
return 1;
}
else {
return undef;
}
}
sub ChangePassword {
my $self = shift;
my $username = shift;
my $password = shift;
my $hash_function = shift;
if (not $username or not $password) {
die "Can't change password: username or password not set.\n";
}
my $entry = $self->UpdateUser(
userName => $username,
password => $password,
hashFunctionName => $hash_function,
);
return $entry;
}
## Nicknames
sub CreateNickname {
}
sub RetrieveNickname {
}
sub RetrieveAllNicknamesForUser {
}
sub RetrieveAllNicknamesInDomain {
}
sub DeleteNickname {
}
# Takes the parsed XML object
sub _build_user_entry {
my $self = shift;
my $xml = shift;
my $entry = VUser::Google::Provisioning::UserEntry->new();
$entry->UserName($xml->{'apps:login'}[0]{'userName'});
if ($xml->{'apps:login'}[0]{'suspended'}) {
if ($xml->{'apps:login'}[0]{'suspended'} eq 'true') {
$entry->Suspended(1);
}
else {
$entry->Suspended(0);
}
}
if ($xml->{'apps:login'}[0]{'changePasswordAtNextLogin'}) {
if ($xml->{'apps:login'}[0]{'changePasswordAtNextLogin'} eq 'true') {
$entry->ChangePasswordAtNextLogin(1);
}
else {
$entry->ChangePasswordAtNextLogin(0);
}
}
if ($xml->{'apps:login'}[0]{'admin'}) {
if ($xml->{'apps:login'}[0]{'admin'} eq 'true') {
$entry->Admin(1);
}
else {
$entry->Admin(0);
}
}
if ($xml->{'apps:login'}[0]{'agreedToTerms'}) {
if ($xml->{'apps:login'}[0]{'agreedToTerms'} eq 'true') {
$entry->AgreedToTerms(1);
}
else {
$entry->AgreedToTerms(0);
}
}
$entry->FamilyName($xml->{'apps:name'}[0]{'familyName'});
$entry->GivenName($xml->{'apps:name'}[0]{'givenName'});
$entry->Quota($xml->{'apps:quota'}[0]{'limit'});
return $entry;
}
no Moose;
__PACKAGE__->meta->make_immutable;
1;
__END__
=head1 NAME
VUser::Google::Provisioning::V2_0 - Support for version 2.0 of the Google Provisioning API
=head1 SYNOPSIS
use VUser::Google::ApiProtocol::V2_0;
use VUser::Google::Provisioning::V2_0;
my $google = VUser::Google::ApiProtocol::V2_0->new(
domain => 'example.com',
admin => 'admin_user',
password => 'secret',
);
my $api = VUser::Google::Provisioning::V2_0->new(
google => $google,
);
## Create user
my $new_user = $api->CreateUser(
userName => 'fflintstone',
givenName => 'Fred',
familyName => 'Flintstone',
password => 'I<3Wilma',
);
## Retrieve a user
my $user = $api->RetrieveUser('fflintstone');
## Retrieve all userr
my @users = $api->RetrieveAllUsers();
## Update a user
my $updated = $api->UpdateUser(
userName => 'fflintstone',
givenName => 'Fredrock',
familyName => 'FlintStone',
suspended => 1,
quota => 2048,
);
## Change password
$updated = $api->ChangePassword('fflintstone', 'new-pass');
$updated = $api->ChangePassword(
'fflintstone',
'51eea05d46317fadd5cad6787a8f562be90b4446',
'SHA-1',
);
$updated = $api->ChangePassword(
'fflintstone',
'd27117a019717502efe307d110f5eb3d',
'MD5',
);
## Delete a user
my $rc = $api->DeleteUser('fflintstone');
=head1 DESCRIPTION
VUser::Google::Provisioning::V2_0 provides support for managing users
using version 2.0 of the Google Provisioning API.
In order to use the Google Provisioning API, you must turn on API support
from the Google Apps for Your Domain control panel. The user that is
used to create the VUser::Google::ApiProtocol object must have administrative
privileges on the domain.
B It's a good idea to log into the web control panel at least once
as the API user in order to accept the the terms of service and admin terms.
If you don't, you'll get intermittent authentication errors when trying to
use the API.
=head2 METHODS
Unless stated otherwise, these methods will die() if there is an API error.
=head3 CreateUser
CreateUser() takes a hash of create options and returns a
VUser::Google::Provisioning::UserEntry object if the account
was created. CreateUser() will die() if there is an error.
The keys of the hash are:
=over
=item userName (required)
The user name of the account to create
=item givenName (required)
The user's given name
=item familyName (required)
The user's family name
=item password (required)
The user's password. If hashFunctionName is also set, this is
the base16-encoded hash of the password. Otherwise, this is the
user's plaintext password.
Google required that passwords be, at least, six characters.
=item hashFunctionName
hashFunctionName must be I or I. If this is set,
password is the base16-encoded password hash.
=item quota
The user's quota in MB.
Not all domains will be allowed to set users'
quotas. If that's the case, creation will still succeed but the
quota will be set to the default for your domain.
=item changePasswordAtNextLogin
If set to a true value, e.g. C<1>, the user will be required to
change their password the next time they login in. This is the default.
You may turn this off by setting changePasswordAtNextLogin to C<0>.
=item admin
If set to a true value, e.g. C<1>, the user will be granted
administrative privileges. A false value, e.g. C<0>, admin rights will
be revoked. By default, users will not be granted admin rights.
=back
=head3 RetrieveUser
my $user = $api->RetrieveUser('fflintstone');
Retrieves a specified user by the user name. RetieveUser will return a
VUser::Google::Provisioning::UserEntry if the user exists and undef
if it doesn't.
=head3 RetrieveUsers
my @users = ();
my %results = $api->RetrieveUsers();
@users = @{ $results{entries} };
while ($results{next}) {
%results = $api->RetrieveUsers($results{next});
push @users, @{ $results{entries} };
}
Fetches one page of users starting at a given user name. Currently,
a page is defined as 100 users. This is useful if you plan on
paginating the results yourself or if you have a very large number
of users.
The returned result is a hash with the following keys:
=over
=item entries
A list reference containing the user accounts. Each entry
is a VUser::Google::Provisioning::UserEntry object.
=item next
The user name for the start of the next page. This will be
undefined (C) if there are no more pages.
=back
See RetrieveAllUsers() if you want
to fetch all of the accounts at once.
=head3 RetrievePageOfUsers
This is a synonym for RetrieveUsers()
=head3 RetrieveAllUsers
my @users = $api->RetrieveAllUsers();
Get a list of all the users for the domain. The entries in the
list are VUser::Google::Provisioning::UserEntry objects.
=head3 UpdateUser
my $updated = $api->UpdateUser(
userName => 'fflintstone',
givenName => 'Fred',
# ... other options
);
Updates an account. UpdateUser takes the same options as CreateUser() but
only userName is required.
UpdateUser() cannot be used to rename an account. See RenameUser().
=head3 RenameUser
my $user_user = $api->RenameUser($oldname, $newname);
Rename an account. The first parameter is the old user name; the
second is the new user name. RenameUser() will die if the old name
does not exist.
=head3 DeleteUser
my $rc = $api->DeleteUser('fflintstone');
Deletes a given user. Returns true if the delete succeded and dies
if there was an error.
=head3 ChangePassword
$updated = $api->ChangePassword('fflintstone', 'new-pass');
$updated = $api->ChangePassword(
'fflintstone',
'51eea05d46317fadd5cad6787a8f562be90b4446',
'SHA-1',
);
$updated = $api->ChangePassword(
'fflintstone',
'd27117a019717502efe307d110f5eb3d',
'MD5',
);
Change a users password.
ChangePassword takes the user name, password and, optionally, a
hash function name. If the hash function name is set, the password,
is the base16-encoded password, otherwise it is the clear text password.
Accepted values for the has function name are I and I.
There is no difference between using this and using UpdateUser to change
the user's password.
=head1 SEE ALSO
=over
=item *
VUser::Google::Provisioning
=item *
VUser::Google::ApiProtocol::V2_0
=item *
VUser::Google::EmailSettings::V2_0
=item *
http://code.google.com/apis/apps/gdata_provisioning_api_v2.0_developers_protocol.html
item *
http://code.google.com/apis/apps/gdata_provisioning_api_v2.0_reference.html
=back
=head1 BUGS
Bugs may be reported at http://code.google.com/p/vuser/issues/list.
=head1 AUTHOR
Randy Smith
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2009 Randall Smith
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
=cut
VUser-Google-Api-1.0.1/lib/VUser/Google/Provisioning/UserEntry.pm 0000644 0001750 0001750 00000002145 11570726510 024420 0 ustar rbsmith rbsmith package VUser::Google::Provisioning::UserEntry;
use warnings;
use strict;
our $VERSION = '0.2.0';
use Moose;
has 'UserName' => (is => 'rw', isa => 'Str');
has 'GivenName' => (is => 'rw', isa => 'Str');
has 'FamilyName' => (is => 'rw', isa => 'Str');
has 'Password' => (is => 'rw', isa => 'Str');
has 'HashFunctionName' => (is => 'rw', isa => 'Str');
has 'Suspended' => (is => 'rw', isa => 'Bool', default => 0);
has 'Quota' => (is => 'rw', isa => 'Int');
has 'ChangePasswordAtNextLogin' => (is => 'rw', isa => 'Bool', default => 0);
has 'Admin' => (is => 'rw', isa => 'Bool', default => 0);
has 'AgreedToTerms' => (is => 'rw', isa => 'Bool', default => 0);
sub as_hash {
my $self = shift;
my %hash = (
userName => $self->UserName,
givenName => $self->GivenName,
familyName => $self->FamilyName,
password => $self->Password,
hashFunctionName => $self->HashFunctionName,
suspended => $self->Suspended,
quota => $self->Quota,
changePasswordAtNextLogin => $self->ChangePasswordAtNextLogin,
admin => $self->Admin,
);
return %hash;
}
no Moose;
__PACKAGE__->meta->make_immutable;
1;
VUser-Google-Api-1.0.1/lib/VUser/Google/EmailSettings/ 0000755 0001750 0001750 00000000000 11570731200 022172 5 ustar rbsmith rbsmith VUser-Google-Api-1.0.1/lib/VUser/Google/EmailSettings/V2_0.pm 0000644 0001750 0001750 00000024472 11570726510 023257 0 ustar rbsmith rbsmith package VUser::Google::EmailSettings::V2_0;
use warnings;
use strict;
# Copyright (C) 2009 Randy Smith, perlstalker at vuser dot org
our $VERSION = '0.1.0';
use Moose;
extends 'VUser::Google::EmailSettings';
# BUG: This should work but doesn't seem to. WTF?
#has '+google' => (isa => 'VUser::Google::ApiProtocol::V2_0');
has '+base_url' => (default => 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/');
## Methods
# Constructor
sub BUILD {}
override 'CreateLabel' => sub {
my $self = shift;
my %options = @_;
my $label = $options{'label'};
$self->google()->Login();
my $url = $self->base_url().$self->google()->domain().'/'.$self->user().'/label';
my $post = "
";
return $self->google->Request('POST', $url, $post);
};
override 'CreateFilter' => sub {
my $self = shift;
my %options = @_;
$self->google()->Login();
my $url = $self->base_url().$self->google->domain().'/'.$self->user().'/filter';
my $post = '
';
## Add criteria
if (defined $options{hasAttachment}) {
$options{hasAttachment} = $options{hasAttachment}? 'true':'false';
}
foreach my $crit qw(from to subject hasTheWord doesNotHaveTheWord hasAttachment) {
if (defined $options{$crit}) {
$post .= sprintf ("",
$crit, $options{$crit});
}
}
## Add actions
foreach my $act qw(shouldMarkAsRead shouldArchive) {
$options{$act} = $options{$act}? 'true':'false';
}
foreach my $act qw(label shouldMarkAsRead shouldArchive) {
if (defined $options{$act}) {
$post .= sprintf ("",
$act, $options{$act});
}
}
$post .= '';
return $self->google->Request('POST', $url, $post);
};
override 'CreateSendAsAlias' => sub {
my $self = shift;
my %options = @_;
my $name = $options{'name'};
my $address = $options{'address'};
my $reply_to = $options{'replyTo'};
my $make_default = $options{'makeDefault'};
$self->google()->Login();
my $url = $self->base_url().$self->google->domain().'/'.$self->user().'/sendas';
my $post = '
';
$post .= "";
$post .= "";
if (defined $reply_to) {
$post .= "";
}
if (defined $make_default) {
$post .= sprintf("",
$make_default? 'true' : 'false'
);
}
$post .= '';
return $self->google->Request('POST', $url, $post);
};
override 'UpdateWebClip' => sub {
my $self = shift;
my %options = @_;
my $enable = $options{'enable'};
$self->google()->Login();
my $url = $self->base_url().$self->google->domain().'/'.$self->user().'/webclip';
my $post = '';
$post .= '';
$post .= sprintf('',
$enable ? 'true' : 'false'
);
$post .= '';
return $self->google->Request('PUT', $url, $post);
};
override 'UpdateForwarding' => sub {
my $self = shift;
my %options = @_;
my $enable = $options{'enable'};
my $forward_to = $options{'forwardTo'};
my $action = $options{'action'};
$action = uc($action);
$self->google()->Login();
my $url = $self->base_url().$self->google->domain().'/'.$self->user().'/forwarding';
my $post = '';
$post .= '';
if (defined $enable) {
$post .= sprintf('',
$enable ? 'true' : 'false');
}
if ($enable) {
if ($forward_to) {
$post .= "";
}
if ($action) {
if ($action ne 'KEEP'
and $action ne 'ARCHIVE'
and $action ne 'DELETE'
) {
die "action must be KEEP, ARCHIVE or DELETE";
}
$post .= "";
}
}
$post .= '';
return $self->google->Request('PUT', $url, $post);
};
override 'UpdatePOP' => sub {
my $self = shift;
my %options = @_;
my $enable = $options{'enable'};
my $enable_for = $options{'enableFor'};
my $action = $options{'action'};
$action = uc($action);
$self->google()->Login();
my $url = $self->base_url().$self->google->domain().'/'.$self->user().'/pop';
my $post = '';
$post .= '';
if (defined $enable) {
$post .= sprintf('',
$enable ? 'true' : 'false');
}
if ($enable) {
if ($enable_for) {
$post .= "";
}
if ($action) {
if ($action ne 'KEEP'
and $action ne 'ARCHIVE'
and $action ne 'DELETE'
) {
die "action must be KEEP, ARCHIVE or DELETE";
}
$post .= "";
}
}
$post .= '';
return $self->google->Request('PUT', $url, $post);
};
override 'UpdateIMAP' => sub {
my $self = shift;
my %options = shift;
my $enable = $options{'enable'};
$self->google()->Login();
my $url = $self->base_url().$self->google->domain().'/'.$self->user().'/imap';
my $post = '';
$post .= '';
if (defined $enable) {
$post .= sprintf('',
$enable ? 'true' : 'false');
}
$post .= '';
return $self->google->Request('PUT', $url, $post);
};
override 'UpdateVacationResponder' => sub {
my $self = shift;
my %options = @_;
my $enable = $options{'enable'};
my $subject = $options{'subject'};
my $message = $options{'message'};
my $contacts = $options{'contactsOnly'};
$self->google->Login();
my $url = $self->base_url().$self->google->domain.'/'.$self->user.'/vacation';
my $post = '';
$post .= '';
$post .= sprintf('',
$enable ? 'true' : 'false');
if (defined $enable) {
$post .= sprintf('',
defined $subject ? $subject : '');
$post .= sprintf('',
defined $message ? $message : '');
$post .= sprintf('',
$contacts ? 'true' : 'false');
}
$post .= '';
return $self->google->Request('PUT', $url, $post);
};
override 'UpdateSignature' => sub {
my $self = shift;
my %options = shift;
my $sig = $options{'signature'};
$self->google->Login();
my $url = $self->base_url().$self->google->domain.'/'.$self->user.'/signature';
my $post = '';
$post .= '';
$post .= sprintf('',
$sig ? $sig : '');
$post .= '';
return $self->google->Request('PUT', $url, $post);
};
override 'UpdateLanguage' => sub {
my $self = shift;
my %options = shift;
my $lang = $options{'language'};
$self->google->Login();
my $url = $self->base_url().$self->google->domain.'/'.$self->user.'/language';
if ($lang !~ /^\w\w(?:-\w\w)?/i) {
$lang = 'en-US';
}
my $post = '';
$post .= '';
$post .= sprintf('',
$lang ? $lang : '');
$post .= '';
return $self->google->Request('PUT', $url, $post);
};
override 'UpdateGeneral' => sub {
my $self = shift;
my %options = @_;
$self->google->Login();
my $url = $self->base_url().$self->google->domain.'/'.$self->user.'/general';
foreach my $opt qw(shortcuts arrows snippets unicode) {
$options{$opt} = $options{$opt}? 'true':'false';
}
my $post = '';
$post .= '';
foreach my $opt (keys %options) {
if (defined $options{$opt}) {
$post .= sprintf ("",
$opt, $options{$opt});
}
}
$post .= '';
return $self->google->Request('PUT', $url, $post);
};
no Moose;
1;
__END__
=head1 NAME
VUser::Google::EmailSettings::V2_0 - Support version 2.0 of the Google Email Settings API
=head1 SEE ALSO
L, L,
L
=over 4
=item Google Email Settings API
http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html
=back
=head1 BUGS
Report bugs at http://code.google.com/p/vuser/issues/list.
=head1 AUTHOR
Randy Smith, perlstalker at vuser dot net
=head1 COPYRIGHT AND LICENSE
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
If you make useful modification, kindly consider emailing then to me for inclusion in a future version of this module.
=cut
VUser-Google-Api-1.0.1/lib/VUser/Google/Provisioning.pm 0000644 0001750 0001750 00000001575 11570726511 022467 0 ustar rbsmith rbsmith package VUser::Google::Provisioning;
use warnings;
use strict;
our $VERSION = '0.2.0';
use Moose;
has 'google' => (
is => 'rw',
isa => 'VUser::Google::ApiProtocol',
required => 1
);
has 'base_url' => (is => 'rw', isa => 'Str');
# Turn on deugging
has 'debug' => (is => 'rw', default => 0);
#### Methods
## Util
#print out debugging to STDERR if debug is set
sub dprint
{
my $self = shift;
my $text = shift;
my @args = @_;
if( $self->debug and defined ($text) ) {
print STDERR sprintf ("$text\n", @args);
}
}
# Escape " with " for XML
sub _escape_quotes {
my $self = shift;
my $text = shift;
$text =~ s/\"/"/;
return $text;
}
# Replace 1 with 'true' other with 0
sub _as_bool {
my $self = shift;
my $value = shift;
return $value ? 'true' : 'false';
}
no Moose;
__PACKAGE__->meta->make_immutable;
1;
__END__
VUser-Google-Api-1.0.1/lib/VUser/Google/Groups.pm 0000644 0001750 0001750 00000001147 11570726511 021253 0 ustar rbsmith rbsmith package VUser::Google::Groups;
use warnings;
use strict;
our $VERSION = '0.2.0';
use Moose;
has 'google' => (
is => 'rw',
isa => 'VUser::Google::ApiProtocol',
required => 1
);
has base_url => (is => 'rw', isa => 'Str');
# Turn on deugging
has 'debug' => (is => 'rw', default => 0);
#### Methods ####
## Util
#print out debugging to STDERR if debug is set
sub dprint
{
my $self = shift;
my $text = shift;
my @args = @_;
if( $self->debug and defined ($text) ) {
print STDERR sprintf ("$text\n", @args);
}
}
no Moose;
__PACKAGE__->meta->make_immutable;
1;
__END__
VUser-Google-Api-1.0.1/lib/VUser/Google/ApiProtocol/ 0000755 0001750 0001750 00000000000 11570731200 021655 5 ustar rbsmith rbsmith VUser-Google-Api-1.0.1/lib/VUser/Google/ApiProtocol/V2_0.pm 0000644 0001750 0001750 00000023267 11570726511 022744 0 ustar rbsmith rbsmith package VUser::Google::ApiProtocol::V2_0;
use warnings;
use strict;
use XML::Simple;
use LWP::UserAgent qw(:strict);
use HTTP::Request qw(:strict);
use Encode;
use Carp;
use Data::Dumper;
use Moose;
extends 'VUser::Google::ApiProtocol';
our $VERSION = '0.5.1';
has 'google_host' => (is => 'ro',
default => 'www.google.com'
);
has 'google_token_url' => (is => 'ro',
default => 'https://www.google.com/accounts/ClientLogin'
);
has 'max_token_age' => (is => 'ro',
default => 86400
);
# base url to the Google REST API
has 'google_baseurl' => (is => 'ro',
default => 'https://www.google.com/a/feeds/'
);
has 'google_apps_schema' => (is => 'ro',
default => 'http://schemas.google.com/apps/2006'
);
has 'success_code' => (is => 'ro',
default => 'Success(2000)'
);
has 'failure_code' => (is => 'ro',
default => 'Failure(2001)'
);
has 'max_name_length' => (is => 'ro', default => '40');
has 'max_username_length' => (is => 'ro', default => '30');
override 'Login' => sub {
my $self = shift;
#print STDERR "LOGIN: debug=".$self->debug."\n";
$self->dprint("Relogin called");
return 1 if $self->IsAuthenticated() and not $self->refresh_token();
my $retval = 0;
my $stats = $self->stats();
$stats->{logins}++;
## Clear last results
$self->_set_reply_headers('');
$self->_set_reply_content('');
$self->_set_result({});
## Create an LWP object to make the HTTP POST request
my $lwp = LWP::UserAgent->new;
if (defined $lwp) {
$lwp->agent($self->useragent);
$lwp->from($self->admin.'@'.$self->domain);
# Submit the request with values for
# accountType, Email and Passwd variables
my $response = $lwp->post($self->google_token_url,
['accountType' => 'HOSTED',
'Email' => $self->admin.'@'.$self->domain,
'Passwd' => $self->password,
'service' => 'apps'
]
);
# save the reply page
$self->_set_reply_headers($response->headers->as_string);
$self->_set_reply_content($response->content);
if ($response->is_success) {
# Extract the authentication token from the response
foreach my $line (split(/\n/, $response->content)) {
$self->dprint("RECV'd: $line");
if ($line =~ m/^Auth=(.+)$/) {
$self->_set_authtoken($1);
$self->_set_authtime(time());
$self->dprint("Token found: %s", $self->authtoken);
# Clear refresh
$self->refresh_token(0);
$retval = 1;
last;
}
}
}
else {
$self->dprint("Error in login: %s", $response->status_line);
$self->_set_result({reason => "Error in login: ".$response->status_line});
}
}
else {
$self->dprint("Error getting LWP object: $!");
$self->_set_result({reason => "Error getting LWP object: $!"});
}
$self->_set_stats($stats);
return $retval;
};
override 'IsAuthenticated' => sub {
#get object reference
my $self = shift();
my $token_age = time - $self->authtime();
if( $self->refresh_token() or ( $token_age > $self->max_token_age() ) ) {
$self->dprint("Refresh token: %s; time-auth: %d; max_age: %d",
$self->refresh_token, $token_age, $self->max_token_age);
return 0;
}
#we are still okay!
return 1;
};
override 'Request' => sub {
my $self = shift;
my $retval = 0;
$self->dprint( "*** REQUEST ***" );
# relogin if needed
$self->Login;
# clear last results
$self->_set_reply_headers('');
$self->_set_reply_content('');
$self->_set_result({});
if (@_ != 2 and @_ != 3) {
$self->_set_result({reason => 'Invalid number of arguments to Request()'});
return 0;
}
# get paramters
my ($method, $url, $body) = @_;
$self->dprint("Method: $method; URL: $url");
$self->dprint("Body: $body") if $body;
## Keep some stats
my $stats = $self->stats;
$stats->{requests}++;
$stats->{rtime} = time;
## Check if we are authenticated to google
if (not $self->IsAuthenticated()) {
$self->dprint("Error autheticating");
$self->_set_stats($stats);
return 0;
}
## Properly encode the body
$body = encode('UTF-8', $body);
## Create an LWP object to make the HTTP POST request
my $ua = LWP::UserAgent->new;
if (not defined $ua) {
$self->dprint("Cannot create LWP::UserAgent: $!");
$self->_set_result({reason => "Cannotcreate LWP::UserAgent in Request: $!"});
$self->_set_stats($stats);
return 0;
}
#and create the request object where are we connecting to
# v2.0 uses a diffent url based what's being done.
# The API methods will construct the URL becuase action specific
# information, such as domain and user, is embedded with it.
# v2.0 use different methods depending on the action
# It's up to the API methods to know which method to use
my $req = HTTP::Request->new($method => $url);
if (not defined $req) {
$self->dprint("Cannot create HTTP::Request object: $!");
$self->_set_result({reason => "Cannot create HTTP::Request object in Request(): $!"});
$self->_set_stats($stats);
return $retval;
}
# Set some user agent variables
$ua->agent($self->useragent);
$ua->from('<'.$self->admin.'@'.$self->domain.'>');
# Submit the request
$req->header('Accept' => 'application/atom+xml');
$req->header('Content-Type' => 'application/atom+xml');
if ($body) {
$req->header('Content-Length' => length($body) );
}
$req->header('Connection' => 'Keep-Alive');
$req->header('Host' => $self->google_host);
$req->header('Authorization' => 'GoogleLogin auth='.$self->authtoken);
# Assign the data to the request
# Perhaps if $method eq 'GET' or 'DELETE' would be better
if ($body) {
$req->content($body);
}
## Execute the request
my $response = $ua->request($req);
$self->dprint(Data::Dumper::Dumper($response));
# Save reply page
$self->_set_reply_headers($response->headers->as_string);
$self->_set_reply_content($response->content);
# Check result
if ($response->is_success) {
$stats->{success}++;
$self->dprint("Success in post:");
my $xml = decode('UTF-8', $response->content);
$self->dprint($xml);
if ($xml) {
## Parse the XML using XML::Simple
my $simple = XML::Simple->new(ForceArray => 1);
$self->_set_result($simple->XMLin($xml));
$self->dprint(Dumper($self->{result}));
}
else {
$self->_set_result({});
}
$self->dprint("Google API success!");
$retval = 1;
}
else {
# OK. Funky issue. When trying to get a user that doesn't exist,
# Google throws a 400 error instead of returning a error document.
# Google has fun. If there is a problem with the request,
# google triggers a 400 error which then fails on ->is_success.
# So, we need to check the content anyway to see if there is a
# reason for the failure.
$self->dprint("Google API failure!");
my $xml = decode('UTF-8', $response->content);
$self->dprint($xml);
if ($xml) {
my $simple = XML::Simple->new(ForceArray => 1);
$self->_set_result($simple->XMLin($xml));
$self->dprint('Error result: %s', Dumper($self->result));
}
if (defined ($self->result()->{error}[0]{reason})) {
my $error = sprintf("Google API failure: %s - %s",
$self->result()->{error}[0]{errorCode},
$self->result()->{error}[0]{reason}
);
$self->dprint($error);
my $res = $self->result;
$res->{reason} = $error;
$self->_set_result($res);
}
else {
$self->dprint("Error in post: %s", $response->status_line);
my $res = $self->result;
$res->{reason} = "Error in post: ".$response->status_line;
$self->_set_result($res);
}
}
return $retval;
};
no Moose;
__PACKAGE__->meta->make_immutable;
1;
__END__
=head1 NAME
VUser::Google::ApiProtocol::V2_0 - Implements version 2.0 of the Google APIs.
=head1 SYSNOPSIS
use VUser::Google::ApiProtocol::V2_0;
## Create a new connection
my $google = VUser::Google::ApiProtocol::V2_0->new(
domain => 'your.google-apps-domain.com',
admin => 'admin_user',
password => 'admin_user password',
);
## Login to the Google Apps API
# Login() uses the credentials provided in new()
$google->Login();
## Create a new request
# Create the URL to send to API request to.
# See the API docs for the valid URLs
my $url = "https://apps-apis.google.com/a/feeds/emailsettings/2.0/"
$url .= "your.google-apps-domain.com/username/label";
# Create XML message to send to Google
# See the API docs for the valid XML to send
my $xml = '...';
# NB: The method (POST here) may be different depending on API call
my $success = $google->Request('POST', $url, $xml);
# Get the parsed response
if ($success) {
# $result is the XML reply parsed by XML::Simple
my $result = $google->get_result;
}
else {
# $result is the error message from google
# parsed by XML::Simple with the addition of a
# 'reason' key which contains the error.
my $result = $google->get_result;
die "Error: $result->{reason}";
}
=head1 DESCRIPTION
Implements version 2.0 of the Google API. See L
for a list of members and methods.
=head1 SEE ALSO
L, L
=head1 AUTHOR
Randy Smith
Adapted from code from Johan Reinalda
=head1 LICENSE
Copyright (C) 2006 by Johan Reinalda, johan at reinalda dot net
Copyright (C) 2009 by Randy Smith, perlstalker at vuser dot org
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.5 or,
at your option, any later version of Perl 5 you may have available.
If you make useful modification, kindly consider emailing then to me for inclusion in a future version of this module.
=cut
VUser-Google-Api-1.0.1/lib/VUser/Google/ApiProtocol.pm 0000644 0001750 0001750 00000014733 11570730671 022236 0 ustar rbsmith rbsmith package VUser::Google::ApiProtocol;
use warnings;
use strict;
use Moose;
our $VERSION = '1.0.1';
## Members
# The Google hosted domain we are accessing
has 'domain' => (is => 'rw');
# The admin account
has 'admin' => (is => 'rw');
# Admin password
has 'password' => (is => 'rw');
# Turn on deugging
has 'debug' => (is => 'rw', default => 0);
# If set, will force re-authentication
has 'refresh_token' => (is => 'rw',
isa => 'Bool',
default => 0,
#init_arg => undef
);
# The authentication token returned from Google
has 'authtoken' => (is => 'rw',
writer => '_set_authtoken',
#init_arg => undef
);
# Time when auth happened; only valid for 24 hours
# Unix timestamp
has 'authtime' => (is => 'rw',
default => 0,
writer => '_set_authtime',
#init_arg => undef
);
# the last http content posted from Google
has 'request_content' => (is => 'rw',
writer => '_set_request_content',
#init_arg => undef
);
# The http headers of the last reply
has 'reply_headers' => (is => 'rw',
writer => '_set_reply_headers',
#init_arg => undef
);
# The http content of the last reply
has 'reply_content' => (is => 'rw',
writer => '_set_reply_content',
#init_arg => undef
);
# The resulting hash from the last reply data as parsed
# by XML::Simple
has 'result' => (is => 'rw',
isa => 'HashRef',
writer => '_set_result',
#init_arg => undef
);
# Some API statistics
has 'stats' => (is => 'rw',
isa => 'HashRef',
default => sub { {ctime => time(), # object creation time
rtime => 0, # time of last request
requests => 0, # number of API requests made
success => 0, # number of successes
logins => 0 # number of authentications
};
},
writer => '_set_stats',
#init_arg => undef
);
has 'useragent' => (is => 'ro',
lazy => 1,
builder => '_build_useragent'
);
has 'version' => (is => 'ro',
builder => '_build_version'
);
## Methods
sub _build_useragent {
my $self = shift;
return ref($self).'/'.$self->version();
}
sub _build_version {
my $self = shift;
my $class = ref($self);
my $ver;
no strict 'refs';
# There has got to be cleaner way to do this.
$ver = eval { ${ $class."::VERSION" } };
$ver = $VERSION if $@;
return $ver;
}
sub Login {}
sub IsAuthenticated {}
#generic request routine that handles most functionality
#requires 3 arguments: Method, URL, Body
#Method is the HTTP method to use. ('GET', 'POST', etc)
#URL is the API URL to talk to.
#Body is the xml specific to the action.
# This is not used on 'GET' or 'DELETE' requests.
sub Request {}
#print out debugging to STDERR if debug is set
sub dprint
{
my $self = shift;
my $text = shift;
my @args = @_;
if( $self->debug and defined ($text) ) {
if (@_) {
print STDERR sprintf ("$text\n", @args);
}
else {
print STDERR "$text\n";
}
}
}
no Moose;
__PACKAGE__->meta->make_immutable;
1;
__END__
=head1 NAME
VUser::Google::ApiProtocol - Base class for implementation of the Google APIs
=head1 SYNOPSIS
This class is not meant to be used directly. Instead use
L.
=head1 DESCRIPTION
=head1 MEMBERS
These are the members of the ApiProtocol class. You get and set the values
by using the method of the same name. For example:
# Get the domain from the ApiProtocol object
my $domain = $google->domain;
# Set the domain
$google->domain('myappsdomain.com');
Most of the member can be set when the object is created with C.
my $google = VUser::ApiProtocol->new(
domain => 'myappsdomain.com'
);
B VUser::Google::ApiProtocol is not meant to be used directly.
Please see the version specific subclasses, such as
L, to create a usable object.
=head2 Read-write Members
=over
=item admin
The administrative user. This user must have be set as an admin in the
Google Apps control panel. Also, be sure to log into the Google Apps control
panel once with this user to accept all of the legal garbage or you will
see intermittent auth errors.
=item debug
Turn on debugging output.
=item domain
The Google Apps domain to work on.
=item password
The plain text password of the admin user.
=item refresh_token
If set to a true value, C will refresh the authentication token
even if it's not necessary.
=back
=head2 Read-only members
=over
=item authtime
The unix timestamp of the last authentication.
=item authtoken
The authentication token retrieved from Google on a successful login.
The token is only valid for 24 hours.
=item reply_headers
The HTTP headers of the last reply
=item reply_content
The HTTP content of the last reply
=item result
The resulting hash from the last reply data as parsed by XML::Simple
=item useragent
The user agent VUser::Google::ApiProtocol uses when talking to Google. It
is set to the I. For example,
I.
=back
=head1 METHODS
=head2 new (%defaults)
Create a new ApiProtocol object. Any read-write member may be set in the
call to C.
=head2 Login
Login to the Google API. C takes no parameters. Instead, you
must set the C, C, and C members, then call
C.
C will use the existing authentication token if it exists and
hasn't yet timed out. You may force it to do a full re-authentication by
setting C to a true value before calling C.
=head2 IsAuthenticated
Returns true if the B