I have this code in NodeMailer for sends email:
var mailOptions = {
from: 'test#test.com',
to: 'send#send.com',
subject: 'mail',
text:'test'
}
And I have this function:
mens.message(params, (err, response) => {
if (err){
res.status(500).json(err);
}
else {
if(response.context.reporte){
-----------> var report = response.context.reporte;
response.context.reporte=null;
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
}
else {
console.log('Email Send: ' + info.response) ;
}
});
}
}
});
How can I do that, this variable "report", that have a message, can replace the "text" attribute of the nodemailer?
Thank you very much!
You need to override the text with the new value
mens.message(params, (err, response) => {
if (err){
res.status(500).json(err);
}
else {
if(response.context.reporte){
var report = response.context.reporte;
response.context.reporte=null;
mailOptions = { ...mailOptions, ...{ text: report } }; // <<<< CHANGE IS HERE
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
}
else {
console.log('Email Send: ' + info.response) ;
}
});
}
}
});
if your node version doesn't support the spread operator then you can replace the mailOptions = { ...mailOptions, ...{ text: report }}, with Object.assign(mailOptions, { text: report });
Related
I have tried to use the following code to retrieve the Lotus user detail by Node.js.
let ActiveDirectory = require('activedirectory');
let config = {
attributes:{user: ["*"]},
url: 'ldap://mylotusdominoserver',
baseDN: 'OU=myOU,O=myOrg',
}
let ad = new ActiveDirectory(config);
ad.authenticate(user, password, function (err, auth) {
if (err) {
console.log('ERROR0: ' + JSON.stringify(err));
return;
}
if (auth) {
console.log('Authenticated!');
let query = "&(objectClass=*)(CN=Amy*)";
ad.find(query, (err, results) => {
if ((err) || (!results)) {
console.log('ERROR1: ' + err);
return;
}
console.log(results.other[0]);
});
}
else {
console.log('Authentication failed!');
}
});
It returns:
Authenticated!
{
dn: 'CN=Amy Tomson,OU=myOU,O=myOrg',
mail: 'amyt#myOU.myOrg',
sn: 'Amy',
cn: 'Amy Tomson'
objectclass: [Array],
givenname: 'Amy',
uid: 'amyt#myOU.myOrg',
maildomain: 'myOrg'
}
However, the return attributes do not include the working title of the user,
I have added the following attributes to force the server to return all attributes of the user.
attributes:{user: ["*"]},
However, it does not work.
My Lotus Note Domino Server version is 9.0.
Is it possible to fix it?
Finally, I use ldapjs library to fix the problem.
Here is the sample code:
const ldap = require('ldapjs');
var client = ldap.createClient({
url: 'ldap://mylotusdominoserver'
});
client.bind(userName, password, function(err) {
if (err) {
console.log('ERROR0: ' + JSON.stringify(err));
return;
}
});
let opts = {
attributes: ['givenname', 'sn', 'uid'],
filter: '&(title=Manager)(uid=*myOU.myOrg)',
scope: "sub",
}
client.search('OU=myOU,O=myOrg', opts, function(err, search) {
if (err) {
console.log('ERROR1: ' + JSON.stringify(err));
return;
}
let results = [];
search.on('searchEntry', function(entry) {
results.push(entry.object);
});
search.on('end', function(entry) {
console.log("End:" + entry.status);
console.log(results);
client.unbind(function(err) {
console.log("Unbinded.");
if (err) {
console.log('ERROR3: ' + JSON.stringify(err));
return;
}
});
});
search.on('error', error => {
if (error) {
console.log('ERROR2: ' + JSON.stringify(error));
return;
}
});
});
I'm using async each to iterate over objects and perform a query to populate their children. Each site has locations which have floors which have areas. My sites and locations populate just fine, however, that is where it stops. Sails outputs that it is looking for floors and areas though but they are never assigned. Any ideas?
gg: function (req, res) {
var userID = req.param('id');
User.findOne({ id: userID }).populate('sites').exec(function afterFind(err, foundUser) {
if (err) return res.json({ status: 'failure', message: 'Server error' });
if (foundUser === undefined) return res.json({ status: 'failure', message: 'User was not found' });
var resultToJson = foundUser.toJSON();
var sites = resultToJson.sites;
async.each(sites, function (site, siteCb) {
sails.log.debug('Finding locations for ' + site.name);
Locations.find({ site: site.id }).exec(function afterFind(err, foundLocations) {
if (err) {
siteCb(err);
} else {
site['locations'] = foundLocations;
async.each(site['locations'], function (location, locCb) {
sails.log.debug('Finding floors for ' + location.name);
Floor.find({ location: location.id }).exec(function afterFind(err, foundFloors) {
if (err) {
locCb(err);
} else {
location['floors'] = foundFloors;
async.each(location['floors'], function (floor, floorCb) {
sails.log.debug('Finding areas for ' + floor.name);
Area.find({ floor: floor.id }).exec(function afterFind(err, foundAreas) {
if (err) {
floorCb(err);
} else {
floor['areas'] = foundAreas;
floorCb();
}
});
}, function (floorError) {
if (floorError) {
locCb(floorError);
}
else {
locCb();
}
});
}
});
}, function (locError) {
if (locError) {
siteCb(locError);
} else {
siteCb();
}
});
}
});
}, function (siteError) {
if (siteError) {
sails.log.debug(siteError);
return res.json({ status: 'failure', message: 'Server error' });
} else {
return res.json({ status: 'success', message: 'Sites for user retrieved', sites: sites });
}
});
});
}
This code should be fixed with use of toJSON() on foundLocations. Anytime when you're overriding a defined attribute with populated one (or something else) it will not work when using a ORM returned object, use toJSON() or something and assign to plain JS object.
Ref: https://stackoverflow.com/a/43500017/1435132
Also, any reason to not use populate with Locations.find?
when running the code below im having an Error: Cannot enqueue Query after invoking quit. i need to insert some data into two table .
can you help me to correct the code im really new here in node.js thank you so much.
Create Contact Service.
router.post('/contactinformationdetails', function (req, res, next) {
try {
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function (err, conn) {
if (err) {
console.error('SQL Connection error: ', err);
return next(err);
} else {
var insertSql1 = "INSERT INTO contact_person SET ? ";
var insertValues1 = {
"site_name": reqObj.sitNam,
"first_name": reqObj.firName,
"last_name": reqObj.lastName,
"position": reqObj.posId,
"contact_number": reqObj.conNum,
"organization": reqObj.orga1,
"email_add": reqObj.emaAdd1,
};
var query = conn.query(insertSql1, insertValues1, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
var Contact_Id = result.insertId;
res.json({
"Cont_id": Contact_Id
});
var insertSql5 = "INSERT INTO address_contactperson SET ? ";
var insertValues5 = {
"address_name": reqObj.addNam,
"address_one": reqObj.addOne,
"address_two": reqObj.addTwo,
"city": reqObj.city,
"province": reqObj.prov
};
var query1 = conn.query(insertSql5, insertValues5, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
});
});
}
});
} catch (ex) {
console.error("Internal error:" + ex);
return next(ex);
}
});
You must try this with mongodb(MongoDB is an open-source document database and leading NoSQL database) the most easy and efficient way.
router.all('/todo/create', function (req, res) {
var taskcreate = req.Collection;
var task = req.body.task;
var date = req.body.date;
var status1 = req.body.status1;
var userid = req.body.userid;
var users = req.Collection;
var record = new taskcreate({
task: task,
date: date,
status1: status1,
userid: userid
});
if (task.length > 0) {
record.save(function (err, result) {
if (err) {
res.json({status: 0, message: err})
} else {
res.json({status: 1, userid: userid, task: task, date: date, message: " success"});
}
})
} else {
res.json({status: 0, msg: "Invalid Fields"});
}
});
[TypeError: Cannot read property 'rid' of undefined]
Is the error that I get when I try to execute this controller on my post route.
I've tested it out with Postman.
I've tried to console.log(result) but I get undefined.
My query gets executed and my row is inserted into my table. I've checked it. Password is also hashed.
The problem is that I don't get any out binds that should be returned.
Problematic code (IMO) is
...
.then(function(result) {
console.log(result);
cb(null, {
id: result.outBinds.rid[0],
email: result.outBinds.remail[0],
role: result.outBinds.rrole[0]
});
})
...
oracle-NodeDB Wrapper
var oracledb = require('oracledb');
module.exports.OBJECT = oracledb.OBJECT;
function executeSQL(config ,sql, bindParams , options) {
return new Promise(function(resolve, reject) {
oracledb.getConnection(
config,
function(err, connection) {
if (err) {
return reject(err);
}
connection.execute(
sql,
bindParams,
options,
function(err, result) {
if (err) {
doRelease(connection);
return reject(err);
}
resolve(result);
doRelease(connection);
});
});
});
}
function doRelease(connection) {
connection.release(
function(err) {
if (err) {
console.log(err.message);
}
}
);
}
module.exports.executeSQL = executeSQL;
Controller
var database = require('../database/oracledbWrapper');
var dbconfig = require('../database/dbconfig').dbconfig;
var jwt = require('jsonwebtoken');
var bcrypt = require('bcrypt');
exports.createUser = function(req, res, next) {
var user = {
email: req.body.email
};
var unhashedPassword = req.body.password;
bcrypt.genSalt(10, function(err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(unhashedPassword, salt, function(err, hash) {
if (err) {
return next(err);
}
user.hashedPassword = hash;
insertUser(user, function(err, user) {
var payload;
if (err) {
return next(err);
}
payload = {
sub: user.email,
role: user.role
};
res.status(200).json({
user: user,
token: jwt.sign(payload, config.jwtSecretKey, {expiresInMinutes: 60})
});
});
});
});
}
function insertUser(user, cb) {
var bindParams = {
email: user.email.toLowerCase(),
password: user.hashedPassword,
rid: {
type: database.NUMBER,
dir: database.BIND_OUT
},
remail: {
type: database.STRING,
dir: database.BIND_OUT
},
rrole: {
type: database.STRING,
dir: database.BIND_OUT
}
};
database.executeSQL(
dbconfig,
'insert into express_users (email, password, role ) values ( :email, :password, \'BASE\' ) returning id, email, role into :rid , :remail, :rrole',
bindParams,
{}
)
.then(function(result) {
console.log(result);
cb(null, {
id: result.outBinds.rid[0],
email: result.outBinds.remail[0],
role: result.outBinds.rrole[0]
});
})
.catch(function(err) {
console.log(err);
next(err);
});
}
Route
var RESTfulAPICon = require('../controllers/RESTfulAPI');
var indexCon = require('../controllers/index');
var views = require('express').Router();
views.route('/users').post(RESTfulAPICon.createUser);
exports.views = views;
The problem was in my wrapper , mainly here
module.exports.OBJECT = oracledb.OBJECT;
I export only the OBJECT property , but I try to access BIND_OUT properties later on. And they are non existent.
If I do the full export like this
module.exports.OBJECT = oracledb;
Then I can access BIND_OUT properties.
Currently I have the following callback system:
var saveTask = function(err, result) {
if (err) return callback(err, result);
var newid = mongoose.Types.ObjectId();
var task = new Task({
_id: newid,
taskname: req.body.name,
teamid: req.body.team,
content: req.body.content,
creator: req.user.userId
});
task.save(function (err) {
if (!err) {
log.info("New task created with id: %s", task._id);
return callback(null, task);
} else {
if(err.name === 'ValidationError') {
return callback('400', 'Validation error');
} else {
return callback('500', 'Server error');
}
log.error('Internal error(%d): %s', res.statusCode, err.message);
}
});
};
if (req.body.team) {
valTeam.isMember(req.body.team, req.user._id, function (err, done) {
if (err) {
saveTask('403', 'Not the owner or member of this team');
} else {
saveTask(null, true);
}
});
} else {
saveTask(null, true);
}
valTeam.isMember
exports.isMember = function(teamid, userid, callback) {
Team.find({'_id':teamid, $or:[{'creator': userid }, {'userlist': { $in : [userid]}}]}, function(err, result) {
if (err) return err;
console.log(result);
if (!result.length)
return callback('404', false);
else
return callback(null, true);
});
}
In short, if team is sent by POST, I'm checking if the user is member of that ID in valTeam.isMember. Am I using the correct syntax and best method to call back my saveTask function to save the task if the user is part of the team?
This code currently works, but I feel like there should be an easier way to do it? How could I use a promise to achieve the same thing?
Thanks in advance.
It's curious the fact that you create objects instead Schemas. However "every head is a different world", this is my way:
task.save(function(error, data){
if (error) {
trow error;
} else {
//Make whatever you want here with data
});