# --
# Kernel/System/Auth/IMAP.pm - provides the IMAP authentification
# Copyright (C) 2006 Michael Weinberger
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (GPL). If you
# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.
# --
# Note:
# available objects are: ConfigObject, LogObject and DBObject
#
# --

package Kernel::System::CustomerAuth::IMAP;

use strict;
use Net::IMAP::Simple;
# Source: http://dag.wieers.com/packages/perl-Net-IMAP-Simple/perl-Net-IMAP-Simple-1.14-1.2.el4.rf.noarch.rpm

use vars qw($VERSION);
$VERSION = '0.1';

# --
sub new {
    my $Type = shift;
    my %Param = @_;

    # allocate new hash for object
    my $Self = {};
    bless ($Self, $Type);

    # check needed objects
    foreach (qw(LogObject ConfigObject DBObject)) {
        $Self->{$_} = $Param{$_} || die "No $_!";
    }

    # Debug 0=off 1=on
    $Self->{Debug} = 0;

    $Self->{Server} = $Self->{ConfigObject}->Get('Customer::AuthModule::IMAP::Server')
      || die "Need CustomerAuthModule::IMAP::Server in Kernel/Config.pm!";

    return $Self;
}
# --
sub GetOption {
    my $Self = shift;
    my %Param = @_;
    # check needed stuff
    if (!$Param{What}) {
        $Self->{LogObject}->Log(Priority => 'error', Message => "Need What!");
        return;
    }
    # module options
    my %Option = (
        PreAuth => 0,
    );
    # return option
    return $Option{$Param{What}};
}
# --
sub Auth {
    my $Self = shift;
    my %Param = @_;
    # check needed stuff
    if (!$Param{User}) {
        $Self->{LogObject}->Log(Priority => 'error', Message => "Need User!");
        return;
    }
    # get params
    my $User = $Param{User} || '';
    my $Pw = $Param{Pw} || '';

	my $imap = Net::IMAP::Simple->new($Self->{Server});

	if( !$imap ) {
        $Self->{LogObject}->Log(
          Priority => 'notice',
          Message => "IMAP auth: IMAP connection to $Self->{Server} failed.",
        );
		return;
		}

	if( $imap->login($User,$Pw) ) {
        $Self->{LogObject}->Log(
          Priority => 'notice',
          Message => "IMAP auth: $User authentication ok.",
        );
  	    return $User;
    }
    else {
        $Self->{LogObject}->Log(
          Priority => 'notice',
          Message => "IMAP auth: $User authentication failed.",
        );
        return;
    }
}
# --

1;
