Cannot read property 'then' of undefined in nodejs - javascript

I have no idea why I encountered that error in my code.
fineOneBySocialLogin(profile).then(function (user) {
}, function (err) {
return done(err, null);
})
var fineOneBySocialLogin = function (req, res) {
auth.findOne({ username: req.emails[0].value }).then(function (user) {
if (!user) {
console.log('testing 1');
var userForm = {};
userForm = {
email: req.emails[0].value
};
user.createUser(userForm).then(function(user) {
if (user) {
console.log('testing 2');
auth.findOne({ username: req.emails[0].value }).then(function (user) {
if (user) {
console.log('testing 3');
return user;
}
});
}
});
} else {
return user;
}
});
}

You should add return before auth.findOne in the second raw.
var fineOneBySocialLogin = function (req, res) {
return auth.findOne({ username: req.emails[0].value }).then(...

should be
return auth.findOne(...

Related

UnhandledPromiseRejectionWarning: TypeError: createUser is not a function

I am having a flow of registering a new user.
I am getting the error UnhandledPromiseRejectionWarning: TypeError: createUser is not a function
auth.js
const express = require("express");
const authrequests = express.Router();
const cors = require("cors");
var createUser = require("./export/authConstants");
// Register User
authrequests.post("/register", async (req, res) => {
const userData = {
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
phone: req.body.phone,
password: req.body.password,
created: new Date(),
};
await createUser(userData)
.then((res) => {
console.log(res)
if (res.status == 200) {
return res.status(200).json({ msg: 'Registered!' });
} else if (res.status == 405) {
return res.status(405).json({ error: 'User already exists' });
} else {
return res.status(400).json({ error: err });
}
})
.catch(err => {
return res.status(400).json({ error: err });
})
});
module.exports = authrequests;
authConstants.js
const customers = require("./../../models/customers");
var hashPassword = require("./util/bcrypt");
var jwtCreate = require("./util/jwt");
var sendMail = require("./util/mail");
var BASE_URL = require("./../constants/constants");
//register
createUser = (userData) => {
return new Promise(async (resolve, reject) => {
customers.findOne({ where: { email: userData.email } })
.then(async (user) => {
if (!user) {
var hashResponse = await hashPassword(userData.password)
if (hashResponse.msg) {
userData.password = hashResponse.msg
customers.create(userData)
.then(async (user) => {
if (user) {
var jwtResponse = await jwtCreate({ data: user.id, expiry: 172800 })
if (jwtResponse.msg) {
const url = `${BASE_URL}/auth/emailVerified/${jwtResponse.msg}`;
var mailResponse = await sendMail({
to: user.email,
subject: 'Email Verification',
html: `Click on the following link to verify your account: click here`
})
if (mailResponse.msg) {
resolve({ status: 200 })
} else {
reject({ error: mailResponse.err })
}
} else {
reject({ error: jwtResponse.err })
}
} else {
reject({ error: "oops..! user creation failed" })
}
})
.catch(err => {
reject({ error: err })
});
} else {
reject({ error: hashResponse.err })
}
} else {
resolve({ status: 405 })
}
})
.catch(err => {
reject({ error: err })
})
})
};
bcrypt.js
const bcrypt = require("bcrypt");
//hashing password
hashPassword = async (password) => {
await bcrypt.hash(password, 10, (err, hash) => {
if (hash) {
return { msg: hash };
} else {
return { error: err };
}
})
};
jwt.js
const jwt = require("jsonwebtoken");
var EMAIL_SECRET = require("./../../constants/constants");
//jwt creation
jwtCreate = async (data) => {
await jwt.sign(data.data, EMAIL_SECRET, { expiresIn: data.expiry }, (err, token) => {
if (token) {
return { msg: token };
} else {
return { error: err };
}
})
};
mail.js
const nodemailer = require("nodemailer");
var MAIL_HOST = require("./../../constants/constants");
var EMAIL_USER = require("./../../constants/constants");
var EMAIL_PASS = require("./../../constants/constants");
//mail send
sendMail = async (data) => {
let transporter = nodemailer.createTransport({
host: MAIL_HOST,
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: EMAIL_USER,
pass: EMAIL_PASS,
},
tls: {
rejectUnauthorized: false,
},
});
await transporter.sendMail({
from: EMAIL_USER,
to: data.to,
subject: data.subject,
html: data.html
}, (err, response) => {
if (token) {
return { msg: response };
} else {
return { error: err };
}
});
};
constants.js
const EMAIL_SECRET = "asdf1093KMnHGcvnkljvasdu09123nlasdasdf";
const MAIL_HOST = "mail.test.com";
const EMAIL_USER = "no_reply_auth#test.com";
const EMAIL_PASS = "JMkC+)*Lv";
const BASE_URL = "http://localhost:3001";
UnhandledPromiseRejectionWarning: TypeError: createUser is not a function
is there something I am missing out..? or the entire flow is wrong..?

async function not returns value but showing after calling undefined typescript

Below is my function returning login token when I debug my function it waits until return but when call function returns undefined and errors are also undefined don't know why it's happening
import userModel from '../Models/user.model';
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken')
let token = null;
process.env.SECRET_KEY = 'secret';
export default class loginController{
static async login(user:any): Promise<any>{
try{
await userModel.findOne({
Email: user.Email
})
.then(async (res:any) => {
if (user) {
if (await bcrypt.compareSync(user.Password, res.Password)) {
const payload = {
Firstname: res.Firstname,
Lastname: res.Lastname,
email: res.Email,
}
token = await jwt.sign(payload, process.env.SECRET_KEY, {
expiresIn: 1400
})
let decoded = jwt.verify(token, process.env.SECRET_KEY)
return token;
}
else {
return "Password is Wrong";
}
}
else {
return 'Please Check Username';
}
})
.catch(err => {
return('error : ' + err)
})
}
catch(err)
{
return err
}
}
}
And my calling function is
const router : Router = Router();
router.post('/login', async (req, res, next) => {
try {
const user = await loginController.login(req.body);
res.json(user)
} catch (error) {
res.json(error)
}
})
I tried call errors it's also debugger waiting until returns value to error but showing undefined
Thanks for the help!
login function doesn't return token because of function scoping. If you have multiple callbacks you can wrap it with a new Promise and use resolve function for returning values.
export default class loginController {
static async login(user: any): Promise<any> {
try {
return new Promise(async (resolve, reject) => {
await userModel
.findOne({
Email: user.Email
})
.then(async res => {
if (user) {
if (await bcrypt.compareSync(user.Password, res.Password)) {
const payload = {
Firstname: res.Firstname,
Lastname: res.Lastname,
email: res.Email
};
const token = await jwt.sign(payload, process.env.SECRET_KEY, {
expiresIn: 1400
});
let decoded = jwt.verify(token, process.env.SECRET_KEY);
resolve(token);
} else {
resolve('Password is Wrong');
}
} else {
resolve('Please Check Username');
}
})
.catch(err => {
resolve('error : ' + err);
});
});
} catch (error) {
return error;
}
}
}

How to avoid 'headers already sent' within Promise chain?

I am working on a 'change password' functionality. I am starting to learn more about Promises and have the following code:
router.post('/change-password', verifyToken, csrfProtection, (req, res, next) => {
if (!req.body.password_current || !req.body.password_new) {
req.flash('info', 'Please fill in both fields.');
return res.redirect('/change-password');
}
const data = {};
data.password = req.body.password_new;
tokenHandler.verifyToken(req.cookies.token)
.then((decoded) => {
return User.findOne({ '_id.user_id': decoded.user });
})
.then((user) => {
data.userId = ObjectId(user._id.user_id);
return bcrypt.compare(req.body.password_current, user.password);
})
.then((allowed) => {
if (!allowed) {
return res.redirect('/change-password');
}
console.log('I am not here');
return User.findOneAndUpdate({ '_id.user_id': data.userId }, { password: data.password }, { new: true });
})
.then(() => {
return res.redirect('/change-password');
})
.catch((err) => {
return next(err);
});
});
I love how Promises are preventing the 'callback hell'. The problem is that I am receiving a 'headers already sent' error. I know that is because I can't escape the chain and that it saves up all the results (unless you throw an Error). To fix the problem I used the following:
router.post('/change-password', verifyToken, csrfProtection, (req, res, next) => {
if (!req.body.password_current || !req.body.password_new) {
req.flash('info', 'Please fill in both fields.');
return res.redirect('/change-password');
}
const data = {};
data.password = req.body.password_new;
tokenHandler.verifyToken(req.cookies.token)
.then((decoded) => {
User.findOne({ '_id.user_id': decoded.user }).then((user) => {
data.userId = ObjectId(user._id.user_id);
bcrypt.compare(req.body.password_current, user.password).then((allowed) => {
if (!allowed) {
return res.redirect('/change-password');
}
User.findOneAndUpdate({ '_id.user_id': data.userId }, { password: data.password }).then((doc) => {
console.log(doc);
return res.redirect('/change-password');
});
});
});
});
});
The question is: Is there a better solution to fix the 'header already sent' error. Because I have the feeling that my solution is actually a few steps away from a 'callback hell' structure.
You can rewrite it like this
router.post('/change-password', verifyToken, csrfProtection, (req, res, next) => {
if (!req.body.password_current || !req.body.password_new) {
req.flash('info', 'Please fill in both fields.');
return res.redirect('/change-password');
}
const data = {};
data.password = req.body.password_new;
tokenHandler.verifyToken(req.cookies.token)
.then((decoded) => {
return User.findOne({ '_id.user_id': decoded.user });
})
.then((user) => {
data.userId = ObjectId(user._id.user_id);
return bcrypt.compare(req.body.password_current, user.password);
})
.then((allowed) => {
if (!allowed) {
return res.redirect('/change-password');
}
else{
console.log('I am not here');
return User.findOneAndUpdate({ '_id.user_id': data.userId }, { password: data.password }, { new: true })
.then(() => {
return res.redirect('/change-password');
});
}
})
.catch((err) => {
return next(err);
});
});
You can return a promise chain from within a then function.
Depending on your version of Node, you may also be able to re-write this using async / await. It generally makes things easier to reason about.
router.post('/change-password', verifyToken, csrfProtection, async (req, res, next) => {
if (!req.body.password_current || !req.body.password_new) {
req.flash('info', 'Please fill in both fields.');
return res.redirect('/change-password');
}
try {
const data = {};
data.password = req.body.password_new;
const decoded = await tokenHandler.verifyToken(req.cookies.token);
const user = await User.findOne({ '_id.user_id': decoded.user });
data.userId = ObjectId(user._id.user_id);
const allowed = await bcrypt.compare(req.body.password_current, user.password);
if (!allowed) {
return res.redirect('/change-password');
} else {
await User.findOneAndUpdate({ '_id.user_id': data.userId }, { password: data.password }, { new: true });
}
return res.redirect('/change-password');
} catch (err) {
return next(err);
}
});
You need Node.js >= 7 to use async/await.

Increment field of another collection in mongodb

I created two collections,one for enterprise and another for employees,their schema is as follows,
var mongoose= require('mongoose');
var Enterprise= new mongoose.Schema({
name:{type:String},
email:{type:String},
sector:{type:String},
employees: {type:Number,default:0}
});
module.exports={
Enterprise:Enterprise
};
var mongoose = require('mongoose');
var employee = new mongoose.Schema({
enterprise:{type: String},
name:{type:String},
email:{type:String},
password:{type:String},
gender:{type:String},
});
module.exports = {
employee:employee
};
my add employee route,
var mongoose = require('mongoose');
var q = require('q');
var employee = mongoose.model('employee');
var enterprise = mongoose.model('enterprise');
var addEmployee = function(req, res) {
newEmployee = new employee();
newEmployee.enterprise = req.params.enterprise;
newEmployee.name = req.params.name;
newEmployee.email = req.params.email;
newEmployee.gender = req.params.gender;
function detailSave() {
var deferred = q.defer();
newEmployee.save(function(err, data) {
if (err) {
res.send(500);
console.log('couldnt save employee details');
deferred.reject({errmessage: 'couldnt save employee details', err: err});
} else {
res.send(200);
deferred.resolve({data: data});
}
});
return deferred.promise;
}
function incrementEmployee(doc) {
var deferred = q.defer();
enterprise.findOneAndUpdate({ 'name': doc.enterprise }, { $inc: { 'employees': 1 } },
function(err, num) {
if (err) {
deferred.reject({errmessage: 'couldnt incrementEmployee', err: err});
res.send(500);
console.log('couldnt incrementEmployee');
} else {
res.send(200);
deferred.resolve({num:num});
}
});
return deferred.promise;
}
detailSave()
.then(incrementEmployee)
.then(function(success) {
console.log('success', success);
res.json(200, success);
})
.fail(function(err) {
res.json(500, err);
})
.done();
};
module.exports = {
addEmployee: addEmployee
};
The problem is when I add an employee, the employees field in enterprise collection doesn't increment
I think your query is not working since doc.enterprise is null
On the basis of your comment.
Try to give your query like this {'name': doc.data.enterprise}
function incrementEmployee(doc) {
var deferred = q.defer();
enterprise.findOneAndUpdate({
'name': doc.data.enterprise
}, {
$inc: {
'employees': 1
}
},
function(err, num) {
if (err) {
deferred.reject({
errmessage: 'couldnt incrementEmployee',
err: err
});
res.send(500);
console.log('couldnt incrementEmployee');
} else {
res.send(200);
deferred.resolve({
num: num
});
}
});
return deferred.promise;
}

Roulette node.js bot "Bot stopped with code null"

I have problem with my node.js bot to roulette. Bot is fully set up but when I launching it, it gives me error "Bot stopped with code null". Can someone help me to fix it?
Here is the error screenshot: http://i.imgur.com/zfZoMD4.png
Code:
function login(err, sessionID, cookies, steamguard) {
if(err) {
logger.error('Auth error');
logger.debug(err);
if(err.message == "SteamGuardMobile") {
account.twoFactorCode = SteamTotp.generateAuthCode(account.shared_secret);
logger.warn('Error in auth: '+account.twoFactorCode);
setTimeout(function() {
community.login(account, login);
}, 5000);
return;
}
process.exit(0);
}
logger.trace('Sucesfully auth');
account.sessionID = sessionID;
account.cookies = cookies;
community.getWebApiKey('csgobananas.com', webApiKey);
community.startConfirmationChecker(10000, account.identity_secret);
}
function webApiKey(err, key) {
if(err) {
logger.error('Cant make apikey')
logger.debug(err);
process.exit(0);
return;
}
account.key = key;
logger.trace('API key bot '+account.accountName+' '+account.key);
offersSetup();
community.loggedIn(checkLoggedIn);
}
function offersSetup() {
logger.trace('Loaded steam-tradeoffers');
offers.setup({
sessionID: account.sessionID,
webCookie: account.cookies,
APIKey: account.key
});
}
function checkLoggedIn(err, loggedIn, familyView) {
if((err) || (!loggedIn)) {
logger.error('We arent logged in')
process.exit(0);
} else {
logger.trace('Logged in');
account.auth = true;
bot_manager.js code:
var forever = require('forever-monitor');
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
database: 'placeholder',
host: 'placeholder',
user: 'placeholder',
password: 'placeholder'
});
query('SELECT * FROM `bots`', function(err, row) {
if((err) || (!row.length)) {
console.log('Failed request or empty bot table');
console.log(err);
return process.exit(0);
}
console.log('List of bots:');
row.forEach(function(itm) {
console.log('Launching bot# '+itm.id);
var bot = new (forever.Monitor)('bot.js', {
args: [itm.id]
});
bot.on('start', function(process, data) {
console.log('Bot with ID '+itm.id+' started');
});
bot.on('exit:code', function(code) {
console.log('Bot stopped with code '+code);
});
bot.on('stdout', function(data) {
console.log(data);
});
bot.start();
});
});
function query(sql, callback) {
if (typeof callback === 'undefined') {
callback = function() {};
}
pool.getConnection(function(err, connection) {
if(err) return callback(err);
console.info('Database connection ID: '+connection.threadId);
connection.query(sql, function(err, rows) {
if(err) return callback(err);
connection.release();
return callback(null, rows);
});
});
}

Categories

Resources