HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Making a "remember login" function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
remembermakingloginfunction

Problem

I'm trying to make a safe "remember me / auto login" function on my site and as I'm just a hobby programmer I would like someone professional to take a look at my code this far. This site will probably never see the light of day I'm just doing this because I find it fun and learning, but I still like to do it correct. I have read this.

Login.php

$query = $db->prepare('SELECT id, username, password FROM users WHERE username = ? OR email = ?');
$query->execute(array($_POST['username'], $_POST['username']));
$row = $query->fetch();

if ($row and password_verify($_POST['password'], $row['password'])) {

    // Remember?
    if (isset($_POST['remember'])) {

        $selector = base64_encode(random_bytes(9));
        $authenticator = random_bytes(33);

        setcookie('remember', $selector.':'.base64_encode($authenticator), time() + 864000);

        $query = $db->prepare('INSERT INTO auth_tokens (selector, token, userid, expires) VALUES (?, ?, ?, ?)');
        $query->execute(array(   $selector, hash('sha256', $authenticator), $row['id'], date('Y-m-d\TH:i:s', time() + 864000)  ));  
    }

    $_SESSION['userid'] = $row['id'];
    $_SESSION['username'] = $row['username'];

    exit(header('Location: /'));
}


This is my logout:

session_destroy();

if (!empty($_COOKIE['remember'])) {
    setcookie('remember', '', time() - 1000);
    $db->exec('DELETE FROM auth_tokens WHERE userid = '.$_SESSION['userid']);
}

exit(header('Location: '.SITE_URL));


And this is my code in index.php to check if the user has the cookie and log them in:

```
if (empty($_SESSION['userid']) && !empty($_COOKIE['remember'])) {

list($selector, $authenticator) = explode(':', $_COOKIE['remember']);

$query = $db->prepare('SELECT * FROM auth_tokens WHERE selector = ?');
$query->execute(array($selector));
$row = $query->fetch();

if (hash_equals($row['token'], hash('sha256', base64_decode($authenticator)))) {
$_SESSION['userid'] = $row['userid'];
}
}

Solution

You are doing good. You are referencing a good example.
The flow will be as below:

-
Once the user logs in and have checked "remember me", set the cookie with a unique token for user.

-
Next time when the user comes back, check the cookie with the token value in DB.

-
If it matches, allow the user to login.

-
If the token is missing redirect to login.

Ref:
http://jaspan.com/improved_persistent_login_cookie_best_practice

Context

StackExchange Code Review Q#154506, answer score: 2

Revisions (0)

No revisions yet.