Example #1
0
function do_login($username = NULL, $password = NULL, $force_login = FALSE)
{
    global $auth_settings;
    destroy_expired_sessions();
    $session_key = $_COOKIE[$auth_settings['cookie_name']];
    $username = trim($username);
    // Check for session if forced login not specified
    if ($force_login != TRUE) {
        $login_id = session_key_to_login_id($session_key);
        if ($login_id !== FALSE) {
            //echo "Session detected!\n<br>";
            return $login_id;
        }
    } else {
        // Destroy any prior session on a forced login
        destroy_session($session_key);
    }
    if (is_null($username)) {
        $username = $_POST['username'];
    }
    if (is_null($password)) {
        $password = $_POST['password'];
    }
    // Don't allow logins for locked out accounts
    $lo = check_lockout($username);
    if ($lo != 0) {
        auth_lockout(NULL, NULL, $username);
        return -1;
    }
    // Authenticate credentials and take lockout actions as required
    $login_id = authenticate_user($username, $password);
    if ($login_id > 0) {
        create_session(NULL, $login_id);
        return $login_id;
    } else {
        destroy_session($session_key);
        // Good user name, bad password
        if ($login_id == -1) {
            auth_lockout(NULL, NULL, $username);
        }
        // Bad user name
        if ($login_id == -2) {
            auth_lockout();
        }
        return -2;
    }
    return -255;
}
// Verify the user has a session; otherwise bounce to login page
require_once 'lib_auth.php';
$uri = $_SERVER['REQUEST_URI'];
if ($validated != TRUE) {
    $validated = FALSE;
}
if (array_key_exists("uri", $_REQUEST)) {
    $r_uri = $_REQUEST['uri'];
} else {
    $r_uri = "index.php";
}
// Don't validate a session that does not exist
if (array_key_exists("php_sa_session", $_COOKIE)) {
    $session_key = $_COOKIE['php_sa_session'];
    destroy_expired_sessions();
    $login_id = session_key_to_login_id($session_key);
    if ($login_id !== FALSE && $login_id !== NULL && $login_id >= 0) {
        $validated = TRUE;
    }
}
// Don't let the user loop on login-specific pages forever
if (preg_match("#/login.php#i", $uri) == 1 || preg_match("#/authenticate.php#i", $uri) == 1) {
    if ($validated == TRUE) {
        //print "<br>validated = true<br>\n";
        $r_uri = preg_replace("/login.php.*/i", "index.php", $r_uri);
        $r_uri = preg_replace("/authenticate.php.*/i", "index.php", $r_uri);
        //print "non-loop redirect: $r_uri\n";
        header("Location: {$r_uri}");
        exit;
    }