#!/usr/bin/perl
#
# This is an external authenticator for Exchange ActiveSync based on:
#
# - Microsoft EAS documentation:
#    http://download.microsoft.com/download/5/D/D/5DD33FDF-91F5-496D-9884-0A0B0EE698BB/%5BMS-ASHTTP%5D.pdf
#
# - mod_auth_external AuthHowTo:
#    http://code.google.com/p/mod-auth-external/wiki/AuthHowTo
#
#   If using mod_auth_external, the caching version is recommended:
#    http://benow.ca/forum/News/Modification%20of%20mod-auth-external%20to%20enable%20authentication%20caching.
#
# - Google's EAS implementation:
#    https://m.google.com/Microsoft-Server-ActiveSync
#
# Usage:
# ~~~~~~
#   o Username is read from first line of stdin
#   o Password is read from second line of stdin
#   o The configured server is connected to and the 'Provision' line used to verify
#     the credentials.
#
# Copyright (c) Andrew Flegg 2012 <andrew@bleb.org>
# Released under the Artistic License.

use strict;
use warnings;
use vars qw($SERVER);
use LWP::UserAgent;
use URI::Escape;

# ---------------------------------------------------------------------
$SERVER = 'm.google.com';
# =====================================================================

my ($user, $pass) = (<STDIN>, <STDIN>);
chomp $user;
chomp $pass;

{
  package AuthAgent;
  our @ISA = qw(LWP::UserAgent);

  sub new {
    my $self = LWP::UserAgent::new(@_);
    $self;
  }

  sub get_basic_credentials {
    return ($user, $pass);
  }
}

my $ua = AuthAgent->new;
my $url = "https://$SERVER/Microsoft-Server-ActiveSync?Cmd=Provision&User=".uri_escape($user).
           '&DeviceId='.uri_escape($0).
           '&DeviceType=SmartPhone';
#print "$url\n";

my $response = $ua->post($url, 'MS-ASProtocolVersion' => '12.0');
my $code = $response->code;
#print "$code\n";
exit 0 if $code != 401;
exit $code;



