<%doc>
$Revision: 1.132 $
</%doc>
<%method checkVersion>
</%method>

<%method checkAuth>
<%doc>
Override this method so that we don't get into a loop.
</%doc>
</%method>

<%method setGlobals>
<& PARENT:setGlobals, dontCare => 1, %ARGS &>
</%method>

<%method getUserInfo>
<& PARENT:getUserInfo, noauth => "1" &>
</%method>

<%method suiteBar>
<& PARENT:suiteBar, noName => 1, noSuiteBarLinks => 1, %ARGS &>
</%method>

<%method header>
<& SELF:mainHeader, bodyType => "nomenu", %ARGS &>
</%method>

<%method title>
Login to ApTest Manager
</%method>

<%args>
$name=>undef
$pass=>undef
$submit=>""
$cancel=>""
$target=>""
</%args>

<%perl>

my $warn       = "" ;
my $user       = undef ;
my $acct       = undef ;
my $sid        = undef ;
my $cookieWarn = 0 ;

my $uRef       = new UserInfo() ;
my $exp        = $uRef->expires() ;
my $supexp     = $uRef->supExpires() ;
my $newVersion = $uRef->checkVersion() ;

$uRef->release() ;

my %cookies = ($ATMConfig::viaCGI) ? fetch CGI::Cookie : CGI::Cookie->fetch ;

my $cookieTop = defined($Framework::cookieTop) ? $Framework::cookieTop : $Framework::webTop ;

### THESE ARE THE CHANGES TO PROCESS EXTERNAL AUTHENTICATION
### Note that these are disabled by default

my $ruser = undef ;

if ( $ATMConfig::allowSSO && defined $ENV{'REMOTE_USER'} ) {
    $ruser = $ENV{'REMOTE_USER'} ;
    # pretend someone clicked the Login button
    $submit = "Login" ;
}

if ( defined $ruser ) {
    $name = $ruser ;
}

if ( defined($name) ) {
    if ( $name eq "" ) {
        $warn .= "You must supply a user name.<br>" ;
    } elsif ( $name =~ m {[^0-9a-zA-Z_\.\-]} ) {
        $warn .= qq(User names may only contain alphanumeric characters, period (.), hyphen (-), and underscore (_).<br \>) ;
    }
    $name =~ s/[^0-9a-zA-Z_\.\-]//g; # strip anything bad from the name

### ADD A CHECK HERE - IF THERE IS A REMOTE USER, THEN WE DONT HAVE THIS
### COOKIE

    if ( !defined $ruser && !exists $cookies{atmCookieTest} ) {
        $warn .= qq(Cookies must be enabled in your browser to log in<br \>) ;
        $cookieWarn = 1 ;
    }

    if ( $warn eq "" ) {
        $acct = new Account(1) ;                 # get a write handle
        $user = new UserInfo( $name, $acct ) ;
        if ( !defined($user) ) {
            if ( $ATMConfig::allowSSO && defined $ENV{REMOTE_USER} ) {
                if ($ATMConfig::autoCreateUsers) {
                    Framework::updateSystemLog( 4, "Auto-creating user $name" ) ;
                    # create a new user account automatically
                    my $userHash = {
                        email       => '',
                        fullname    => $name,
                        password    => 'NoLoGiN',
                        phoneNumber => '',
                        timezone    => Framework::localTimeZone(1),
                        timestyle   => $ATMConfig::timestyle,
                        rowsPerPage => $ATMConfig::reportRows,
                        encrypted   => 0,
                        emailOn     => 0,
                        startPage   => 'default'
                    } ;
                    if ( $acct->userInfo( $name, $userHash ) ) {
                        if ($ATMConfig::suiteAccess == "none") {
                            # if the default access level is none, then we only need to build the
                            # access list for any new suites
                            $acct->buildUserHash( [] ) ;
                        } else {
                            $acct->buildUserHash( ) ;
                        }
                        $acct->buildUserHash( ) ;
                        $acct->lastChange( time() ) ;
                        $acct->save(1) ;
                        $user = new UserInfo( $name, $acct ) ;
                        Notify->notify(
                            trigger => 'userChange',
                            message => "Account $name auto-created.",
                            account => $acct
                        ) ;
                    }
                } else {
                    Framework::updateSystemLog( 1, "User $name authenticated, but no such user" ) ;
                }
            }
            if ( !defined $user ) {
                if ($ATMConfig::caseInsensitiveLogin) {
                    $warn .= qq(The user $name does not exist. Please note user names are case sensitive.) ;
                } else {
                    $warn .= qq(The user $name does not exist.) ;
                }
                Framework::updateSystemLog( 1, "Login failed  - no such user $name" ) ;
            }


        } elsif ( !defined $ruser && !$user->authenticate($pass) ) {
            # see if there might be some LDAP-y problem
            if ( $user->disabled() ) {
                $warn .= "This account is disabled.  Contact your system administrator." ;
            } elsif ( $user->fromLDAP() && !ApTest::LDAP::isActive( $user->serverNum() ) && !defined $user->password() ) {
                $warn .= "This account is tied to an LDAP server, but this copy of ApTest Manager is no longer associated with that LDAP server. Please contact your system administrator to have a password assigned assigned to this account." ;
            } else {
                $warn .= "That password is incorrect. Please note passwords are case sensitive." ;
            }
            if ( defined $ATMConfig::logBadPassword && $ATMConfig::logBadPassword ) {
                Framework::updateSystemLog( 1, "Login failed for user $name - bad password $pass" ) ;
            }
        } else {
            if ($ATMConfig::CLOSED) {
                my $acl = $user->acl() ;
                if ( !defined $acl || !defined $acl->{'account'}
                    || ( $acl->{'account'} ne "yes" ) ) {
                    $warn .= "That user is not an administrator - Please select another." ;
                    Framework::updateSystemLog( 1, "User $name tried to log in whilst closed and is not an admin" ) ;
                    goto handleWarn;
                }
            }
            $sid = $user->login() ;
            if ( !defined $sid ) {
                $warn .= "There are already " . $user->maxUsers() . " logged in users - the maximum permitted by your license." ;
                Notify->notify(
                    trigger => 'systemAlert',
                    message => 'A user was unable to use ApTest Manager because all license seats were in use.'
                ) ;

                Framework::updateSystemLog( 1, "User limit reached, maxUsers is " . $user->maxUsers() ) ;
            }
        }
    }
}
  handleWarn:
if ( defined($user) && ( $warn eq "" ) && $submit eq "Login" ) { # no warnings, complete the login
    my $suite = $userInfo->setting('lastSelectedSuite') ;
    $suite = Framework::checkSuite( $user, $suite ) ;

    my $dest = "index.mpl" ;
    if ( defined $target && ( $target ne "" ) ) {
        $dest = $target ;
    } elsif ( defined $suite && defined $user->startPage ) {
        $dest = $user->startPageURL() . '?suite=' . $suite ;
    }
    if ( $name eq "admin" ) {
        $dest = "accounts/index.mpl" ;
    }
    if ( my $msg = $user->shouldNotify() ) {
        # there is a pending notification...
        Notify->notify(
            trigger => 'updateAvailable',
            message => $msg,
            account => $acct,
        ) ;
    }

    # make sure the database is up to date
    $user->{acct} = undef ;
    $acct->save(1) ;
    $acct->release() ;
    Framework::updateSystemLog( 2, "Logging in user $name" ) ;

    if ( $ENV{'SERVER_SOFTWARE'} =~ /Microsoft-IIS/ ) {
        Framework::updateSystemLog( 10, "Setting cookie as $sid" ) ;
        if ($ATMConfig::viaCGI) {
            $m->comp( "SELF:header_out", name => 'Set-Cookie', value => $sid ) ;
            Framework::updateSystemLog( 10, "Cookie being pushed in CGI mode" ) ;
        } else {
            $m->comp( "SELF:err_header_out", name => 'Set-Cookie', value => $sid ) ;
            Framework::updateSystemLog( 10, "Cookie being pushed in mod_perl mode" ) ;
        }
</%perl>
<p class="title">Logged in as user <% $name |h %>.</p>
<script type="text/javascript" language="javascript1.1">
	top.location.href='<% $dest %>'
</script>
<%perl>
    } else {
        $m->comp( "SELF:redirect", cookie => $sid, location => $dest ) ;
    }
} else {
    $acct->release() if ( defined $acct ) ;
    if ( $cancel eq "Cancel" ) {
        $m->out("<p>Login process canceled.</p>") ;
    } else {
        my $testCookie = CGI::Cookie->new(
            -name    => 'atmCookieTest',
            -value   => 'test',
            -path    => $cookieTop,
            -expires => undef
        ) ;
        Framework::updateSystemLog( 10, "Setting test cookie as $testCookie" ) ;
        if ($ATMConfig::viaCGI) {
            $m->comp( "SELF:header_out", name => 'Set-Cookie', value => $testCookie ) ;
            Framework::updateSystemLog( 10, "Cookie being pushed in CGI mode" ) ;
        } else {
            $m->comp( "SELF:err_header_out", name => 'Set-Cookie', value => $testCookie ) ;
            Framework::updateSystemLog( 10, "Cookie being pushed in mod_perl mode" ) ;
        }
</%perl>

<noscript>
<p><b>This product requires the availability of JavaScript 1.2 or
greater.  Please enable JavaScript and reload this page.</b></p>
</noscript>

<div class='indent'>
%         if ( defined $newVersion && !$ATMConfig::isHosted ) {
%             $newVersion =~ s/(http:.*?)\n/<a target="_blank" href="$1">$1<\/a>\n/ ;
%             $newVersion =~ s/\n/<br \>/g ;
<% Framework::warning(qq(<p>$newVersion</p>)) %>
%         }

%         if ($exp) {
%             my $thing = "expires" ;
%             $thing = "expired" if ( $exp < time() ) ;
<p>The license for this copy of ATM <% $thing %> on <% Framework::fmtTime( $exp, 1, "at" ) %>.
%             if ( !$ATMConfig::isHosted ) {
This is a temporary license issued when the software was purchased.
A permanent license will be issued to you upon 
receipt of payment. 
%             }
</p>
%         }

%         if ( $supexp && !$ATMConfig::isHosted ) {
%             if ( $supexp < time() + ( 30 * 24 * 60 * 60 ) ) {
%                 # if we are within 30 days
%                 my $thing = "expires" ;
%                 $thing = "expired" if ( $supexp < time() ) ;
<p>The support contract for this copy of ApTest Manager <% $thing %> on <% Framework::fmtTime( $supexp, 1, "at" ) %>.</p>
% }}

%         if ( !$exp || $exp > time() ) {
%             if ($ATMConfig::CLOSED) {
%                 $m->out("<table width='90%' border='0'><tr><td><img alt='Forbidden' src='$Framework::webTop/images/fixed/forbidden.gif' height='48' width='48' border='0'></td> <td> This copy of ApTest Manager is open to administrators only at this time due to maintenance or other administrative activities. Please check back later or contact your site administrator.</td></tr></table><br>") ;
%             }
%             $m->out("<table border='0'><tr><td><img src='$Framework::webTop/images/fixed/error.gif' height='48' width='48' border='0'></td> <td> $warn </td></tr></table><br>") if ( $warn ne "" ) ;

%             if ( !$cookieWarn ) {
%                 if ($ATMConfig::MOTD) {
<% $ATMConfig::MOTD %>
%                 }

<script type="text/javascript" language="JavaScript">
<!--

document.cookie = 'atmCookieTest=test';

//-->
</script>

<p class="title">Please enter your user name and password</p>
<form id="theForm" action="login.mpl" method="post">
<table class="bordered">
<tr><td>User name:</td><td>
<input value="<% $name |h %>" type="text" name="name" maxlength="50" size="30">
</td></tr>
<tr><td>Password:</td><td><input value="" type="password" name="pass" maxlength="30" size="30"></td></tr>
</table>
<p><input class="bbutton" value="Login" type="submit" name="submit">&nbsp;<input class="bbutton" type="submit" name="cancel" value="Cancel">&nbsp;<input class="bbutton" type="reset"><input type="hidden" name="target" value="<% $target |h %>">
</form>
%                 if ($ATMConfig::createAccount) {
<p>If you don't have an user account, you can <a href="accounts/createAccount.mpl">create one</a>.</p>
%                 }

%             } else {

<p>Please enable cookies before <a href="./login.mpl?target=<% $target | u %>">continuing</a>.</p>

%             }

%         }

</div>
% }}

<%once>
use Account ;
use Notify ;
use ApTest::LDAP ;
</%once>
