<?php
$logid = 'Password';

require_once("Smarty/Smarty.class.php");
require_once("util.php");
require_once("message.php");
require_once("config.php");

session_start();

$message = '';
$userattr = isset($conf['userattr']) ? $conf['userattr'] : 'uid';

$ldap = @ldap_connect($conf['uri']);
$rc = @ldap_bind($ldap, $conf['binddn'], $conf['bindpw']);
if (!$rc) {
    $log->err(logformat("Login failed: ". ldap_error($ldap)));
    $message = USS_ERR_002;
}

if ($rc && isset($_POST['username']) && $_POST['username']) {
    $username = $_POST['username'];
    $password = isset($_POST['loginpass']) ? $_POST['loginpass'] : '';

    $res = @ldap_search($ldap, $conf['basedn'], "($userattr=$username)");
    if ($res !== false && ldap_count_entries($ldap, $res) == 1) {
        $entries = ldap_get_entries($ldap, $res);
        $userdn = $entries[0]['dn'];
    } else if ($res === false) {
        $log->err(logformat("Login failed: ". ldap_error($ldap)));
        $message = USS_ERR_002;
        $rc = false;
    } else {
        $log->err(logformat("Login failed: user or password is invalid"));
        $message = USS_ERR_004;
        $rc = false;
    }

    if ($rc) {
        $password = isset($_POST['loginpass']) ? $_POST['loginpass'] : '';
        $rc = @ldap_bind($ldap, $userdn, $password);
        if (!$rc) {
            $log->err(logformat("Login failed: user or password is invalid"));
            $message = USS_ERR_004;
        } else {
            $log->info(logformat("Login succeeded"));
            $_SESSION['username'] = $username;
            $_SESSION['userdn'] = $userdn;
        }
    }
}

if (isset($_SESSION['username']) && $_SESSION['username']) {
    $app = isset($_GET['app']) ? $_GET['app'] : 'password';
    if ($app == 'secret') {
        require_once('secret.php');
    } else {
        require_once('password.php');
    }
} else {
    $smarty = new Smarty();
    $smarty->template_dir = 'templates';
    $smarty->compile_dir = 'templates_c';

    $smarty->assign('message', $message);
    $smarty->assign('uri', $_SERVER['SCRIPT_NAME']);
    $smarty->display('login.tpl');
}
?>
