# Copyright (C) 2005 FishGrove Inc.
#
# 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# $Id: WSSE.pm,v 1.5 2006/03/07 14:39:11 slash5234 Exp $

package Affelio::misc::WSSE;
{
    use strict;
    use lib("../../../extlib/");
    use Digest::SHA1;
    use MIME::Base64 ();
    use Error qw(:try);
    use lib("../../../lib/");
    use Affelio::misc::Debug;
    use Exporter;
    @Affelio::misc::WSSE::ISA = "Exporter";
    @Affelio::misc::WSSE::EXPORT = qw(make_XWSSE authenticate);

    sub authenticate {
	my ($XWSSE_mesg, $user, $pass) = shift;	
	return(1);

	my $my_own_mesg = make_XWSSE($user, $pass);

	if($my_own_mesg eq $XWSSE_mesg){
	    return(1);
	}else{
	    return("");
	}
    }

    sub make_XWSSE {
	my ($user, $pass) = shift;
	
	my $now = now_w3cdtf();
	my $nonce = make_nonce();
	my $nonce_enc = MIME::Base64::encode_base64($nonce, '');
	my $digest = MIME::Base64::encode_base64( Digest::SHA1::sha1($nonce . $now . $pass), '' );
	
	my $wsse_value = 'UsernameToken ' . join(
						 ', ',
						 qq(Username="$user"),
						 qq(PasswordDigest="$digest"),
						 qq(Nonce="$nonce_enc"),
						 qq(Created="$now"),
						 );

	return($wsse_value);
    }


    sub make_nonce {
	return Digest::SHA1::sha1(Digest::SHA1::sha1(time() . {} . rand() . $$));
    }

    sub now_w3cdtf {
	my ($sec, $min, $hour, $mday, $mon, $year) = gmtime();
	$mon++; $year += 1900;
	
	return sprintf(
		       "%04s-%02s-%02sT%02s:%02s:%02sZ",
		       $year, $mon, $mday, $hour, $min, $sec,
		       );
    }


}#package
1;
