File size: 2,046 Bytes
9705b6c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
const { User, Key } = require('../../models');
const { encrypt, decrypt } = require('../utils');
const updateUserPluginsService = async (user, pluginKey, action) => {
try {
if (action === 'install') {
return await User.updateOne(
{ _id: user._id },
{ $set: { plugins: [...user.plugins, pluginKey] } },
);
} else if (action === 'uninstall') {
return await User.updateOne(
{ _id: user._id },
{ $set: { plugins: user.plugins.filter((plugin) => plugin !== pluginKey) } },
);
}
} catch (err) {
console.log(err);
return err;
}
};
const getUserKey = async ({ userId, name }) => {
const keyValue = await Key.findOne({ userId, name }).lean();
if (!keyValue) {
throw new Error('User-provided key not found');
}
return decrypt(keyValue.value);
};
const getUserKeyExpiry = async ({ userId, name }) => {
const keyValue = await Key.findOne({ userId, name }).lean();
if (!keyValue) {
return { expiresAt: null };
}
return { expiresAt: keyValue.expiresAt };
};
const updateUserKey = async ({ userId, name, value, expiresAt }) => {
const encryptedValue = encrypt(value);
return await Key.findOneAndUpdate(
{ userId, name },
{
userId,
name,
value: encryptedValue,
expiresAt: new Date(expiresAt),
},
{ upsert: true, new: true },
).lean();
};
const deleteUserKey = async ({ userId, name, all = false }) => {
if (all) {
return await Key.deleteMany({ userId });
}
await Key.findOneAndDelete({ userId, name }).lean();
};
const checkUserKeyExpiry = (expiresAt, message) => {
const expiresAtDate = new Date(expiresAt);
if (expiresAtDate < new Date()) {
const expiryStr = `User-provided key expired at ${expiresAtDate.toLocaleString()}`;
const errorMessage = message ? `${message}\n${expiryStr}` : expiryStr;
throw new Error(errorMessage);
}
};
module.exports = {
updateUserPluginsService,
getUserKey,
getUserKeyExpiry,
updateUserKey,
deleteUserKey,
checkUserKeyExpiry,
};
|