request.session.regenerate not working, undefined 'undefined' - javascript

I've got this issue:
request.session.regenerate(function() {
request.session.user = username;
return response.send(username);
});
When logging in I always get undefined error:
Cannot read property 'regenerate' of undefined
If I just leave return response.send(username); it works fine, however I need to create a session.
What could be the issue?
More code
router.post('/login', bodyParser, function(request, response) {
var username = request.body.username;
var password = request.body.password;
adminUser.findOne({
username: username
}, function(err, data) {
if (err | data === null) {
return response.send(401, "User Doesn't exist");
} else {
var usr = data;
if (username == usr.username && bcrypt.compareSync(password, usr.password)) {
request.session.regenerate(function() {
request.session.user = username;
return response.send(username);
});
} else {
return response.send(401, "Bad Username or Password");
}
}
});
});
Added: app.use (session());
Now its working.

Making my comment into an answer since it appears to have solved your issue...
Express does not automatically have request.session. You have to be using some middleware that creates that like express-session. If you are using express-session, then you would add:
const session = require('express-session');
and
app.use(session({secret: 'my super secret'}));

Related

NodeJS SQL Login Error (ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client)

Hello I'm pretty new to nodeJS and I'm having an issue which I believe the catalyst is in the second if statement nested in "db.query..." in the code below. Im getting an error that says ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client but I'm not quite sure how to fix this situation? I'm trying to create a login form which gets the information from mysql.
app.post('/login',(req, res) =>{
const { email, password } = req.body //pulls name="email" from html
if(email && password){
db.query('SELECT * from users WHERE email = ? ;',[email], function (err, result) {
if (err) throw err;
if (result) {
if(result[0].password === password){
req.session.userId = result[0].uid
return res.redirect('/home')
}
}
console.log(result[0].email)
});
}
res.redirect('/login')
});
You need to wait until your query execution completes.
In Your code the response was send to client before your query returns result.
You can try something like following.
app.post('/login', async (req, res) =>{
const { email, password } = req.body //pulls name="email" from html
if(email && password){
try {
let result = await db.query('SELECT * from users WHERE email = ? ;',[email]);
if (result) {
if(result[0].password === password){
req.session.userId = result[0].uid
return res.redirect('/home')
} else {
res.redirect('/login')
}
}
} catch(e) => {
res.redirect('/login')
}
}
}

How to fix "Error: Can't set headers after they are sent" in Express

I have recently been developing a MERN application and I have recently came into the trouble that express is saying that I am setting headers after they are sent.
I am using mongo db and trying to update a user profile.
I have tried to comment out my res.send points to find the issue but I have failed to do so.
Here is my post method for updating the user profile:
app.post("/api/account/update", (req, res) => {
const { body } = req;
// Validating and Checking Email
if (body.email) {
var email = body.email;
email = email.toLowerCase();
email = email.trim();
body.email = email;
User.find(
{
email: body.email
},
(err, previousUsers) => {
if (previousUsers.length > 0) {
return res.send({
success: false,
message:
"Error: There is already another account with that email address"
});
} else {
}
}
);
}
// Validating Names Function
function checkName(name) {
var alphaExp = /^[a-zA-Z]+$/;
if (!name.match(alphaExp)) {
return res.send({
success: false,
message: "Error: Names cannot contain special characters or numbers"
});
}
}
checkName(body.firstName);
checkName(body.lastName);
// Making sure that all fields cannot be empty
if (!body.email && !body.firstName && !body.lastName) {
return res.send({
success: false,
message: "Error: You cannot submit nothing"
});
}
// Getting User ID from the current session
UserSession.findById(body.tokenID, function(err, userData) {
// Finding User ID using the current users session token
if (userData.isDeleted) {
return res.send({
success: false,
message:
"Error: Session token is no longer valid, please login to recieve a new one"
});
}
// Deleting the token ID from the body object as user table entry doesnt store tokens
delete body.tokenID;
// Finding the user profile and updating fields that are present
User.findByIdAndUpdate(userData.userId, body, function(err, userInfo) {
if (!err) {
return res.send({
success: true,
message: "Success: User was updated successfully"
});
}
});
});
});
This is the call that I am doing to the backend of the site:
onUpdateProfile: function(fieldsObj) {
return new Promise(function(resolve, reject) {
// Get Session Token
const obj = getFromStorage("the_main_app");
// Defining what fields are getting updated
fieldsObj.tokenID = obj.token;
// Post request to backend
fetch("/api/account/update", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(fieldsObj)
})
.then(res => {
console.log("Verify Token - Res");
return res.json();
})
.then(json => {
console.log("Verify Token JSON", json);
if (json.success) {
window.location.href = `/manage-account?success=${json.success}`;
} else {
window.location.href = `/manage-account?success=${json.success}`;
}
});
});
}
Here is my error message that I am getting:
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (C:\Users\kieran.corkin\Desktop\Projects\Mern Template Final\mern-cra-and-server\server\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (C:\Users\kieran.corkin\Desktop\Projects\Mern Template Final\mern-cra-and-server\server\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\kieran.corkin\Desktop\Projects\Mern Template Final\mern-cra-and-server\server\node_modules\express\lib\response.js:267:15)
at ServerResponse.send (C:\Users\kieran.corkin\Desktop\Projects\Mern Template Final\mern-cra-and-server\server\node_modules\express\lib\response.js:158:21)
at C:\Users\kieran.corkin\Desktop\Projects\Mern Template Final\mern-cra-and-server\server\routes\api\account.js:270:22
at C:\Users\kieran.corkin\Desktop\Projects\Mern Template Final\mern-cra-and-server\server\node_modules\mongoose\lib\model.js:4641:16
at process.nextTick (C:\Users\kieran.corkin\Desktop\Projects\Mern Template Final\mern-cra-and-server\server\node_modules\mongoose\lib\query.js:2624:28)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
[nodemon] app crashed - waiting for file changes before starting...
Can anyone help me with this?
EDIT
I have changed my code, this seems to now work however I feel like its a little messy when put together. Any refactoring tips?
Code:
app.post("/api/account/update", (req, res) => {
// Preform checks on data that is passed through
const { body } = req;
var messages = {
ExistedUser:
"Error: There is already another account with that email address",
NameFormat: "Error: Names cannot contain special characters or numbers",
BlankInputs: "Error: You cannot submit nothing",
accountLoggedOut:
"Error: Session token is no longer valid, please login to recieve a new one",
successfullyUpdated: "Success: User was updated successfully"
};
var usersFound;
if (body.email) {
var email = body.email;
email = email.toLowerCase();
email = email.trim();
body.email = email;
User.find(
{
email: body.email
},
(err, UserCount) => {
usersFound = UserCount;
}
);
}
function capitalize(text) {
return text.replace(/\b\w/g, function(m) {
return m.toUpperCase();
});
}
if (body.firstName) {
body.firstName = capitalize(body.firstName);
}
if (body.lastName) {
body.lastName = capitalize(body.lastName);
}
//Making sure that all fields cannot be empty
if (!body.email && !body.firstName && !body.lastName) {
return res.send({
success: false,
message: messages.BlankInputs
});
}
// Getting User ID from the current session
UserSession.findById(body.tokenID, function(err, userData) {
// Finding User ID using the current users session token
if (userData.isDeleted) {
return res.end({
success: false,
message: messages.accountLoggedOut
});
}
if (userData) {
// Deleting the token ID from the body object as user table entry doesnt store tokens
delete body.tokenID;
// Finding the user profile and updating fields that are present
User.findByIdAndUpdate(userData.userId, body, function(err, userInfo) {
if (userInfo) {
if (!usersFound.length > 0) {
return res.send({
success: true,
message: messages.successfullyUpdated
});
} else {
return res.send({
success: false,
message: messages.ExistedUser
});
}
}
});
}
});
});
You're calling res.send() twice. res.send() ends the process. You ought to refactor such that you call res.write() and only call res.send() when you're done.
This StackOverflow link describes the difference in more detail. What is the difference between res.send and res.write in express?
I believe this is happening, as you're trying to send a response after the first / initial response has already been sent to the browser. For example:
checkName(body.firstName);
checkName(body.lastName);
Running this function twice is going to try and yield 2 different "response" messages.
The product of a single route, should ultimately be a single response.
Thanks for all your help on this issue.
Here is my final code that allowed it to work.
I have also tried to "refactor" it too. Let me know if you'd do something else.
app.post("/api/account/update", (req, res) => {
const { body } = req;
console.log(body, "Logged body");
// Defining objects to be used at the end of request
var updateUserInfo = {
userInfo: {},
sessionToken: body.tokenID
};
var hasErrors = {
errors: {}
};
// Checking that there is at least one value to update
if (!body.email && !body.firstName && !body.lastName) {
var blankError = {
success: false,
message: "Error: You cannot change your details to nothing"
};
hasErrors.errors = { ...hasErrors.errors, ...blankError };
} else {
console.log("Normal Body", body);
clean(body);
console.log("Cleaned Body", body);
updateUserInfo.userInfo = body;
delete updateUserInfo.userInfo.tokenID;
}
// Function to check if object is empty
function isEmpty(obj) {
if (Object.keys(obj).length === 0) {
return true;
} else {
return false;
}
}
// Function to remove objects from body if blank
function clean(obj) {
for (var propName in obj) {
if (obj[propName] === "" || obj[propName] === null) {
delete obj[propName];
}
}
}
// Checking and Formatting Names Given
function capitalize(text) {
return text.replace(/\b\w/g, function(m) {
return m.toUpperCase();
});
}
if (body.firstName) {
body.firstName = capitalize(body.firstName);
}
if (body.lastName) {
body.lastName = capitalize(body.lastName);
}
// Checking and formatting email
if (body.email) {
body.email = body.email.toLowerCase();
body.email = body.email.trim();
// Checking for email in database
User.find({ email: body.email }, (err, EmailsFound) => {
if (EmailsFound.length > 0) {
var EmailsFoundErr = {
success: false,
message: "There is already an account with that email address"
};
hasErrors.errors = { ...hasErrors.errors, ...EmailsFoundErr };
}
});
}
// Getting User Session Token
UserSession.findById(updateUserInfo.sessionToken, function(err, userData) {
// Finding User ID using the current users session token
if (userData.isDeleted) {
var userDeletedError = {
success: false,
message:
"Your account is currently logged out, you must login to change account details"
};
hasErrors.errors = { ...hasErrors.errors, ...userDeletedError };
} else {
// Finding the user profile and updating fields that are present
User.findByIdAndUpdate(
userData.userId,
updateUserInfo.userInfo,
function(err, userInfo) {
// userInfo varable contains user db entry
if (err) {
var updateUserError = {
success: false,
message: "Error: Server Error"
};
hasErrors.errors = {
...hasErrors.errors,
...updateUserError
};
}
if (isEmpty(hasErrors.errors)) {
res.send({
success: true,
message: "Success: You have updated your profile!"
});
} else {
res.send({
success: false,
message: hasErrors.errors
});
}
}
);
}
});
});

MongoDB & React : db.find() returns undefined after closing it

So, when I first open the connection with the database, all is working fine, but when I close it and try to re-open it, the db object gives no error but returns undefined ...
Here's how I open the connection :
let conn = null;
let db = null;
async function validateLoginForm(payload, res) {
const errors = {};
let isFormValid = true;
let message = '';
if (!payload || typeof payload.email !== 'string' || payload.email.trim().length === 0) {
if (payload.email !== 'anonymous') {
isFormValid = false;
errors.email = 'Please provide your email address.';
}
}
if (!payload || typeof payload.password !== 'string' || payload.password.trim().length === 0) {
if (payload.email !== 'anonymous') {
isFormValid = false;
errors.password = 'Please provide your password.';
}
}
let stringConnection = payload.email === 'anonymous' ? 'mongodb://ds133221.mlab.com:33221/sandbox-te' : 'mongodb://' + payload.email + ':' +
payload.password + '#ds133221.mlab.com:33221/sandbox-te';
conn = await MongoClient.connect(stringConnection, await function(err, dbase) {
if (err)
{
isFormValid = false;
let errorMessage = 'Error connecting to DB';
return res.status(400).json({
success: false,
message: errorMessage,
errors: errors
});
}
else
{
db = dbase;
if (payload.email !== 'anonymous')
{
let roles = dbase.command({usersInfo: {user: payload.email, db: 'sandbox-te'}, showCredentials: true}, (err, result) => {
if (result.users[0] && result.users[0].roles[0] &&
(result.users[0].roles[0].role === 'dbOwner' || result.users[0].roles[0].role === 'readWrite'))
{
dbase.close();
return res.status(200).json({
success: true,
hasWriteRole: true
})
}
});
}
else
{
return res.status(200).json({
success: true,
hasWriteRole: false
})
}
}
});
}
The first part of the file validates a login form and the second part uses the email and password to try to open a connection with the database.
The whole function just works fine, but when I try to re-open it in the same file but another function, it won't work :
router.post('/search', (req, res) => {
db.open((err, dbase) => {
let test = dbase.collection('test');
console.log(test);
let promiseOfFind = test.find({}).toArray((err, docs) => {
console.log(docs); // RETURNS UNDEFINED ONLY IF DB WAS CLOSED EARLIER
})
});
});
If I don't close the database in the validateLoginForm function, I can retrieve documents without having to open it again, but I just want to achieve this..
What is wrong with my code ? I'm pretty new to Javascript and the API reference of the official MongoDB driver for node.js doesn't help much..
I'm using latest versions of React, Express, MongoDB official Driver for Node.JS, and of course, Node.JS
Thanks in advance !
With MongoDB you should open a single connection and re-use it through your application. You don't need the promises you've got then.
So on startup:
const connection = MongoClient.connect(stringConnection, function(err, dbase) {
// Start web server
});

ASYNC issue on node.js

I'm new to node and I tried to make a basic app with authentification . Data are stored on a mongoDB remote server.
My HTML form POST data to my server URL.
Here the route :
app.post('/auth', function(req, res){
handleRequest(req, res);
});
And the called handler :
function handleRequest(request, response) {
if (request.method == 'POST') {
console.log("Trying to get POST");
var body = '';
request.on('data', function (data) {
body += data;
});
// Get datas, parse them and create user with it
request.on('end', function () {
var data = JSON.parse(body);
var login = data.login;
var password = data.password;
var email = data.email;
myUser = userClass.create(login,email,password);
console.log ("email : "+email);
console.log ("password : "+password);
// authenticate with user
var auth = userClass.authenticate(myUser,function(result){
console.log("result = "+result);
});
});
}
}
The userClass.authenticate :
exports.authenticate = function(user,callback){
var result = "false";
var query = User.where(
{
email : user.email,
password : user.password
});
query.findOne(function(err,user){
if(err){return handleError(err);}
if(user){
result = "true";
}
console.log(user);
});
console.log("callback inc")
callback(result);
}
I'm pretty sure it's not optimized but it's not what I'm looking for.
When I launch the server and I send it some POST (correct) data, this strange thing happens :
My user stored in remote DB is found , so in userClass.authenticate result = true
But when the callback function is ran, the log say it's false. Did I do a something wrong in the callback ?
if query.findOne is Asynchronous, you're calling the callback before findOne is complete. Put the callback(result) inside the findOne callback - like this
exports.authenticate = function(user,callback){
var result = "false";
var query = User.where(
{
email : user.email,
password : user.password
});
query.findOne(function(err,user){
if(err){return handleError(err);}
if(user){
result = "true";
}
console.log(user);
callback(result);
});
}

Node js custom callback function error

I'm trying to make a simple authentication with node js. Because I read user data from a database, I have to make it asynchronous. Here's my function, which checks if authentication is ok:
function auth(req, callback) {
var header = req.headers['authorization'];
console.log(cb.type);
console.log("Authorization Header is: ", header);
if(!header) {
callback(false);
}
else if(header) {
var tmp = header.split(' ');
var buf = new Buffer(tmp[1], 'base64');
var plain_auth = buf.toString();
console.log("Decoded Authorization ", plain_auth);
var creds = plain_auth.split(':');
var name = creds[0];
var password = creds[1];
User.findOne({name:name, password:password}, function(err, user) {
if (user){
callback(true);
}else {
callback(false);
}
});
}
}
And here I call the function:
auth (req, function (success){
if (!success){
res.setHeader('WWW-Authenticate', 'Basic realm="myRealm');
res.status(401).send("Unauthorized");
}else{
if(user!==req.user) {
res.status(403).send("Unauthorized");
}else{
User.findOneAndUpdate({user:userid}, {user:req.body.user, name:req.body.name, email:req.user.email, password:User.generateHash(req.body.password)},
{upsert:true}, function(err, user) {
if(!err) {
res.status(200).send("OK");
}else{
res.status(400).send("Error");
}
});
}
}
});
This gives me error "TypeError: object is not a function", pointing at "callback(false)". I have no idea what could cause this error, as I pass a function as a parameter, and the first log message prints "[function]". Any help would be appreciated.

Categories

Resources