seepur/app/Utils/Redis/ExpiredToken.js

57 lines
1.4 KiB
JavaScript

const Redis = use('Redis');
const Logger = use('Logger');
const {v4: uuidv4} = require('uuid');
const TOKEN_NAMESPACE = 'expired_token';
const TokenTypes = {
RP: 'rp',
};
class ExpiredToken {
/**
*
* @param {{id:number; email:string}} payload
* @param {number} ttl in seconds default 86400 (24 hours)
*/
static async generateResetPasswordToken(payload, ttl = 86400) {
try {
Logger.debug(`Generating RP token`);
const token = `${TokenTypes.RP}_${uuidv4()}`;
const rdKey = `${TOKEN_NAMESPACE}:${token}`;
await Redis.set(rdKey, JSON.stringify(payload));
await Redis.expire(rdKey, ttl);
return token;
} catch (e) {
Logger.error(`Failed to generate RP token. Error: ${e.message}`);
return null;
}
}
/**
*
* @param {string} token
*/
static async getTokenPayload(token) {
try {
const response = await Redis.get(`${TOKEN_NAMESPACE}:${token}`);
if (response) return JSON.parse(response);
return null;
} catch (e) {
Logger.error(`Failed to generate RP token. Error: ${e.message}`);
return null;
}
}
static async remove(token) {
try {
await Redis.del(`${TOKEN_NAMESPACE}:${token}`);
return true;
} catch (e) {
Logger.error(`Failed to generate RP token. Error: ${e.message}`);
return false;
}
}
}
module.exports = ExpiredToken;