package MT::Authenz2;

use strict;
use warnings;

use Apache2::Access ();
use Apache2::RequestRec ();
use Apache2::RequestUtil ();

use Apache2::Const -compile => qw(OK DECLINED HTTP_UNAUTHORIZED);

use MT::App ();
use MT::Author ();

sub handler {
    my $r  = shift;

    my ($status, $password) = $r->get_basic_auth_pw;
    return $status unless $status == Apache2::Const::OK;

    my $config_file = $r->dir_config('MTConfig');
    my $mt_dir = $r->dir_config('MTHome');
    my %params = (Config => $config_file, ApacheObject => $r,
                  ( $mt_dir ? ( Directory => $mt_dir ) : () ));
    my $app = bless MT->new( %params ), 'MT::App'
        or return Apache2::Const::DECLINED;

    $app->{init_request} = 1;
	 $app->init(%params);

    my ($user, $authed);
    if ($user = $app->session_user($r->user, $password)
			 and
		 ref $user and ref $user eq 'MT::Author'
			 and ($user->is_superuser() or
			 $user->type() == MT::Author::AUTHOR)) {
		 $authed = 1;
	 }

    $app->takedown();

	 return Apache2::Const::OK
		 if $authed;

    $r->note_basic_auth_failure;
    return Apache2::Const::HTTP_UNAUTHORIZED;
}

1;

