#!/usr/bin/perl -Tw
# Remove the "-Tw" above to turn of taint checks
use Net::OpenID::Consumer;
use LWPx::ParanoidAgent;
use CGI qw/:standard/;
$cgi = new CGI;
$script_url="http://localhost/openid-cgi/index.cgi";
$test_identity="www.livejournal.com/users/robla/";
$trust_root="http://localhost/";
my $csr = Net::OpenID::Consumer->new(
  ua    => LWPx::ParanoidAgent->new,
  args  => $cgi,
);
sub next_step {
    my($next_url, $step_num) = @_;
    my $fast=0;
    
    if($fast) {
	print redirect($next_url);
    }
    else {
	print header,
	      start_html("OpenID: Step $step_num"),
	      h1("OpenID: Step $step_num");
	print "$next_url";
	exit;
    }
}
# Step 0
if(!param()) {
    print header,
	  start_html("OpenID: Step $step_num"),
	  h1("OpenID: Step 0");
    print "Start now";
    exit;
}
# a user entered, say, "bradfitz.com" as their identity.  The first
# step is to fetch that page, parse it, and get a
# Net::OpenID::ClaimedIdentity object:
if(!param('openid.mode')) {
    my $claimed_identity = $csr->claimed_identity($test_identity);
    if($csr->errcode) {
	print "Content-type: text/html\n\n";
	print $csr->err;
	die $csr-err;
    }
    # now your app has to send them at their identity server's endpoint
    # to get redirected to either a positive assertion that they own
    # that identity, or where they need to go to login/setup trust/etc.
    my $check_url = $claimed_identity->check_url(
        return_to  => $script_url,
        trust_root => $trust_root,
    );
    next_step($check_url, 1);
}
# so you send the user off there, and then they come back to
# openid-check.app, then you see what the identity server said;
if (my $setup_url = $csr->user_setup_url( post_grant => "return" )) {
    next_step($setup_url, 2);
} elsif (my $vident = $csr->verified_identity) {
    print header,
          start_html("OpenID: Yay!"),
          h1("OpenID: Yay!");
    my $verified_url = $vident->url;
    print "You are $verified_url !";
} else {
    print header,
          start_html("OpenID: Boo!"),
          h1("OpenID: Boo!");
    die "Error validating identity: " . $csr->err;
}