Files
ember-market-frontend/backend/models/Wallet.model.js
2025-03-10 17:39:37 +00:00

56 lines
1.5 KiB
JavaScript

import mongoose from "mongoose";
import crypto from "crypto";
// Set default values if environment variables are not available
const encryptionKeyHex = process.env.ENCRYPTION_KEY || '48c66ee5a54e596e2029ea832a512401099533ece34cb0fbbb8c4023ca68ba8e';
const encryptionIvHex = process.env.ENCRYPTION_IV || '539e26d426cd4bac9844a8e446d63ab1';
const algorithm = "aes-256-cbc";
const encryptionKey = Buffer.from(encryptionKeyHex, "hex");
const iv = Buffer.from(encryptionIvHex, "hex");
function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, encryptionKey, iv);
let encrypted = cipher.update(text, "utf8", "hex");
encrypted += cipher.final("hex");
return encrypted;
}
function decrypt(text) {
const decipher = crypto.createDecipheriv(algorithm, encryptionKey, iv);
let decrypted = decipher.update(text, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}
const WalletSchema = new mongoose.Schema({
walletName: {
type: String,
},
orderId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Order",
required: true,
unique: true,
},
address: {
type: String,
required: true,
},
encryptedPrivateKey: {
type: String,
required: true,
},
});
WalletSchema.pre("save", function (next) {
if (!this.isModified("encryptedPrivateKey")) return next();
this.encryptedPrivateKey = encrypt(this.encryptedPrivateKey);
next();
});
WalletSchema.methods.getDecryptedPrivateKey = function () {
return decrypt(this.encryptedPrivateKey);
};
export default mongoose.model("Wallet", WalletSchema);