Kenneth .J
Kenneth .J

Reputation: 1433

How do i make a token expire

I'm trying to code a password recovery script with PHP, and after having a look around here in SO, the consensus for best practice seems to be

I currently have functions to generate a token, but how would i go about making it expire?Also, what would be a good shelf-life for the token?

Token Generation code:

    function crypto_rand_secure($min, $max) {
        $range = $max - $min;
        if ($range < 0) return $min; // not so random...
        $log = log($range, 2);
        $bytes = (int) ($log / 8) + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ($rnd >= $range);
        return $min + $rnd;
}

function GenerateToken($length){
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    for($i=0;$i<$length;$i++){
        $token .= $codeAlphabet[crypto_rand_secure(0,strlen($codeAlphabet))];
    }
    return $token;
}

P.s the code above was copy-pasted from another question here on S.O

Upvotes: 4

Views: 20068

Answers (4)

Dimitris Maniatis
Dimitris Maniatis

Reputation: 177

Fetch the input email form my db. Generate and store a token with length 10 mixed with 0123456789qwertzuioplkjhgfdsayxcvbnm in my db. Send Email with the params and UPDATE users SET token to expire after 5 min.

**   <?php
    if (isset($_POST["forgotPass"])) {
        $connection = new mysqli("localhost", "root", "", "");

        $email = $connection->real_escape_string($_POST["email"]);

        $data = $connection->query("SELECT id FROM users WHERE email='$email'");

        if ($data->num_rows > 0) {
            $string = "0123456789qwertzuioplkjhgfdsayxcvbnm";
            $string = str_shuffle($string);
            $string = substr($string, 0, 10);
            $url = "resetPassword.php?token=$string&email=$email";

            mail($email, "Reset password", "To reset your password, please visit this: $url", "From: [email protected]\r\n");

            $connection->query("UPDATE users SET token='$string', expire = DATE_ADD(NOW(), INTERVAL 5 MINUTE) WHERE email='$email'");

            echo "Please check your email!";
        } else {
            echo "Please check your inputs!";
        }
    }
?>
<html>
    <body>
        <form action="forgotPassword.php" method="post">
            <input type="text" name="email" placeholder="Email"><br>
            <input type="submit" name="forgotPass" value="Request Password">
        </form>
    </body>
</html>                           

**

Upvotes: 0

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44874

You can do this way

create a table called password_recovery with the following fields

  • id Primary Key auto incremented
  • iduser int(11) // length you may choose as per your requirement
  • token_key varchar(100) // length you may choose as per your requirement
  • expire_date datetime
  • created_date datetime

Now while someone request for password recovery usually by entering login name or email get the iduser for that user. Then generate a token. You can set the expire_date as you want. Lets say its 1 day from now, you can use strtotime() to generate that. Insert these values in the password_recovery table.

Then send the email to the users email id something like

yourdomain.com/passrecover.php?h=[token from above]

Once user clicks on the link, run a code to check if the token is valid and if not expired . If so display the password reset form. You will have the iduser from that token. Else display the error message.

Finally once user reset the password , delete the row from the table.

You can in addition have a cronjob script to delete the expired tokens from the table.

Upvotes: 9

user180100
user180100

Reputation:

Persist somewhere the token and its expiration (storage). On the landing page, when you see the token, you:

  • check if the token is present in storage (if not it's a bad token)
  • check the token expiration date
  • do your landing page thing (password change or something)
  • remove the token from storage (not a good token anymore)

Upvotes: 0

norlesh
norlesh

Reputation: 1861

To make it expire you need to store the creation date either on your system or somehow encoded in the token and check this when the token is redeemed.

Upvotes: 1

Related Questions