Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • Generate Token with expiry
  • Send token via email to user
  • User clicks on token and changes password.

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

like image 682
Kenneth .J Avatar asked Sep 12 '25 21:09

Kenneth .J


2 Answers

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.

like image 196
Abhik Chakraborty Avatar answered Sep 15 '25 09:09

Abhik Chakraborty


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.

like image 44
norlesh Avatar answered Sep 15 '25 09:09

norlesh