https://supertokens.com/ logo
about password reset
s

saaymeen

05/25/2023, 7:45 PM
Hey, I have a question about a blog article published on your website here: https://supertokens.com/blog/implementing-a-forgot-password-flow It is about the generation and implementation of OTP tokens for password resets. The post is written super well and it is easy to follow. One technical detail that I stumbled upon however is the generation of the OTP tokens. In the database schema, you define the tokens as unique:
CREATE TABLE password_reset_tokens (    
    user_id VARCHAR(36) NOT NULL,    
    token VARCHAR(128) NOT NULL UNIQUE,    
    token_expiry BIGINT UNSIGNED NOT NULL,    
    PRIMARY KEY (user_id, token),
); โ€
This is likely to prevent users from having to include their ID in a request payload, because on password reset actions, generated tokens can directly be mapped back to the actual accounts. While I noticed that many popular websites actually include the account ID on password reset (e.g. Reddit in a JWT that is exposed in the reset URL sent to the user), this is just an observation and not my point. How do you actually ensure that there are no collisions when generating the tokens before inserting them into a database? While it is statistically very, very unlikely to find collisions in a truly random 128 character string (or is it that just the hash for a token with less chars?), there still is a theoretical chance. Futhermore, if those tokens are actually simpler (4 or 6 character strings, think of app input forms or similar), chances of collisions become much higher. Now I am wondering, does the approach in the blog post actually differ much from those where the strings are actually used to be directly entered in forms, does the application logic generate random tokens until a unused one is found (which would be one iteration most of the time anyway), or am I missing something? Cheers!
r

rp

05/26/2023, 5:49 AM
hey @saaymeen
We ensure unique tokens by regenerating them and trying again (in a loop) in case there is a unique constraint failure when inserting the new token in the db
> does the application logic generate random tokens until a unused one is found Yes. A new token is generated each time for the same user if they keep on requesting the password reset tokens, and when any one of them is consumed, all of them are revoked
s

saaymeen

05/26/2023, 6:03 AM
Thanks for clarifying, thatโ€™s why I assumed ๐Ÿ‘๐Ÿผ