package MyApache::AuthMemCookie;

use strict;
use CGI::Cookie ();
use Apache2::Const -compile => qw(OK REDIRECT FORBIDDEN AUTH_REQUIRED);
use Apache2::Log;
use Cache::Memcached;
use vars qw($VERSION);
$VERSION = '0.01';

use Data::Dumper;

=pod

=head1 B<Login2 - Complete the login cycle by redirecting back to the RESUMEPATH>

=head2 B<Module Usage>

=over
  This module is used to take the place of Apache2 authmemcookie for the use
  of integration with simpleSAMLphp

    perlModule MyApache::AuthMemCookie
    PerlAuthenHandler MyApache::AuthMemCookie::authen_handler
    ErrorDocument 401 "/simplesaml/authmemcookie.php"
    <Location /location_to_protect>
       PerlSetVar AuthMemCookie "NameOfCookie"
       PerlSetVar AuthMemServers "127.0.0.1:11211, /var/sock/memcached"
       PerlSetVar AttrsInHeaders 1
       AuthType Cookie
       AuthName "My Login"
       Require valid-user
    </Location>

=back

=cut

our $memd = undef;

     
sub authen_handler {
  
    my $r = shift;

    # first, remove all headers and env vars that might have been injected
    foreach my $k (keys %ENV) {
        delete $ENV{$k} if $k =~ /^(ATTR_|UserName)/;
    }
    foreach my $h (keys %{$r->headers_in}) {
        $r->headers_in->unset($h) if $h =~ /^(ATTR_|UserName)/;
    }

    # what is our cookie called
    my $cookie_name = $r->dir_config("AuthMemCookie") ? $r->dir_config("AuthMemCookie") : 'AuthMemCookie';
    print STDERR "Headers in: ".Dumper($r->headers_in);

    # sort out our memcached connection
    unless ($memd) {
        my @memd_servers = split /\s*(?:,)\s*/, ($r->dir_config("AuthMemServers") ? $r->dir_config("AuthMemServers") : '127.0.0.1:11211, /var/sock/memcached');
        $memd = new Cache::Memcached {
            'servers' => [ @memd_servers ],
            'debug' => 0,
            'compress_threshold' => 10_000,
           };
        print STDERR "memcache serves: ".Dumper(\@memd_servers);
    }

    # get and process the cookies 
    my $cookies = $r->headers_in->get('Cookie');
    $cookies = parse CGI::Cookie($cookies);
    my $auth_cookie = exists $cookies->{$cookie_name} ? $cookies->{$cookie_name}->value() : "";

    # do we have the AuthMemCookie?
    unless ($auth_cookie) {
        $r->log_error("AuthMemCookie does not exist ($cookie_name) -> forcing login");
        return Apache2::Const::AUTH_REQUIRED;
    }
    print STDERR Dumper($auth_cookie);
    my $val = $memd->get($auth_cookie);

    # Do we have a valid Memcached session?
    unless ($val) {
        $r->log_error("Memcached session not found for AuthMemCookie ($cookie_name): $auth_cookie");
        return Apache2::Const::AUTH_REQUIRED;
    }

    $r->log_error("AuthMemCookie value: $val");

    # we found a valid MemCache session so push it into the environment and let them go
    my %vars = map { my ($k, $v) = split(/=/, $_, 2); $k => $v } (split(/\r\n/, $val));

    # should the values be set in the headers
    my $header_switch = $r->dir_config("AttrsInHeaders") ? $r->dir_config("AttrsInHeaders") : 0;
    my $user = "";
    foreach my $k (keys %vars) {
      if ($k eq "UserName") {
          $user = $vars{$k};
      }
      if ($header_switch) {
          $r->headers_in->add($k => $vars{$k});
#          $r->log_error("setting header: $k => ".$vars{$k});
      }
      else {
          $ENV{$k} = $vars{$k};
#          $r->log_error("setting environment var: $k => ".$vars{$k});
      }
    }
      $r->log_error("The user name is: $user");
    $r->user($user);
    return Apache2::Const::OK;
}
     
# don't forget 1;
1;

