add the redis
This commit is contained in:
@@ -1,19 +1,20 @@
|
||||
//app/utils/emailVerification.util.js
|
||||
// app/utils/emailVerification.util.js
|
||||
|
||||
const crypto = require("crypto");
|
||||
|
||||
/**
|
||||
* Generate a cryptographically secure
|
||||
* random email-verification token.
|
||||
*/
|
||||
const redis = require("../config/redisClient");
|
||||
|
||||
const EMAIL_VERIFICATION_TTL =
|
||||
Number(
|
||||
process.env.EMAIL_VERIFICATION_TTL_SECONDS
|
||||
) || 1800;
|
||||
|
||||
const generateEmailVerificationToken = () => {
|
||||
return crypto.randomBytes(32).toString("hex");
|
||||
return crypto
|
||||
.randomBytes(32)
|
||||
.toString("hex");
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Hash verification token before
|
||||
* storing it in database.
|
||||
*/
|
||||
const hashEmailVerificationToken = (token) => {
|
||||
return crypto
|
||||
.createHash("sha256")
|
||||
@@ -21,8 +22,82 @@ const hashEmailVerificationToken = (token) => {
|
||||
.digest("hex");
|
||||
};
|
||||
|
||||
const createEmailVerification = async (userId) => {
|
||||
|
||||
// 1. Generate raw token
|
||||
const token =
|
||||
generateEmailVerificationToken();
|
||||
|
||||
|
||||
// 2. Hash token
|
||||
const tokenHash =
|
||||
hashEmailVerificationToken(token);
|
||||
|
||||
|
||||
// 3. Create Redis key
|
||||
const redisKey =
|
||||
`email-verification:${tokenHash}`;
|
||||
|
||||
await redis.set(
|
||||
redisKey,
|
||||
userId,
|
||||
"EX",
|
||||
EMAIL_VERIFICATION_TTL
|
||||
);
|
||||
|
||||
return token;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Check a verification token.
|
||||
*/
|
||||
const verifyEmailVerificationToken =
|
||||
async (token) => {
|
||||
|
||||
if (
|
||||
!token ||
|
||||
typeof token !== "string"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
// 1. Hash token received from user
|
||||
const tokenHash =
|
||||
hashEmailVerificationToken(token);
|
||||
|
||||
|
||||
// 2. Build same Redis key
|
||||
const redisKey =
|
||||
`email-verification:${tokenHash}`;
|
||||
|
||||
|
||||
// 3. Search Redis
|
||||
const userId =
|
||||
await redis.get(redisKey);
|
||||
|
||||
if (!userId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
userId,
|
||||
redisKey,
|
||||
};
|
||||
};
|
||||
|
||||
const deleteEmailVerification =
|
||||
async (redisKey) => {
|
||||
|
||||
await redis.del(redisKey);
|
||||
};
|
||||
|
||||
|
||||
module.exports = {
|
||||
generateEmailVerificationToken,
|
||||
createEmailVerification,
|
||||
verifyEmailVerificationToken,
|
||||
deleteEmailVerification,
|
||||
hashEmailVerificationToken,
|
||||
};
|
||||
Reference in New Issue
Block a user