A user can generate an API key by pressing a button, and I save the API key in the database. However, I don't save it as plain text, but rather hash it. I thought this was wise until I started trying to verify the API key.
I am hashing like this:
const saltRounds = 10;
const key = crypto.randomUUID();
const hashedToken = await bcrypt.hash(key, saltRounds);
The problem now is that in the other application, the user doesn't send any user details like email address for example. So, if they had I could have done a findOne({email: email})
or if there was a user ID I could have done findById
etc. but now only the API key is sent.
So, I am receiving the plain text version of the API key and need to somehow compare it.
I would have done the below but I don't actually have user.apiKey
.
const validKey = await bcrypt.compare(key, user.apiKey);
So, if all I have is the plain text API key, how can I find it and compare it in the database?