Can't assign req.session.user when is called fs.mkdir - node.js

This is the code of the app.post that calls fs.mkdir by the function that I made, newdir:
app.post('/register', express.bodyParser(), function (req, res, next){
var newu = new UserModel({});
newu.user = req.body.nuser;
newu.pass = req.body.npass;
newu.mail = req.body.nmail;
UserModel.find({ user: req.body.user }, function (err, user){
if (user.lenght == 1) {
res.redirect('/');
}
else {
newdir(req.body.nuser);
next()
if (err) throw err;
newu.save(function (err, newu){
req.session.user = newu.user;
res.redirect('/home')
});
}
});
});
This is the code of newdir:
function newdir (username){
var pathu = __dirname + '/users/' + username;
fs.mkdir(pathu, function (err){
if (err) throw err;
});
}
An this is the code of /home:
app.get('/home', function (req, res){
console.log(req.session.user);
res.send('Welcome ' + req.session.user + '!');
});
I can assign a req.session.user in all app.post/get that I want, for example when I verify the user with this, I can assign the req.session.user correctly:
app.post('/verify', express.bodyParser(), function (req, res){
UserModel.find({ user: req.body.user }, function (err, user){
if (user[0] == undefined) {
res.redirect('/');
}
else{
if (user[0].pass == req.body.pass) {
req.session.user = user[0].user;
res.redirect('/home');
}
else{
res.redirect('/');
}
}
if (err) throw err;
});
});
But when I try to assign req.session.user in the same app.post where's it's called fs.mkdir, always req.session.user is undefined. Maybe I should create a module that makes the fs.mkdir call? I don't know what to do!

The problem is resolved when fs.mkdir is called in other module, very simple :D

Related

How to pass Data Between multiple routes in express?

app.post("/login", passport.authenticate("local",), function (req, res) {
const user = new Model({
username: req.body.username,
password: req.body.password,
});
req.login(user, function (err) {
if (err) {
console.log("wrong password");
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/admin");
});
}
});
});
app.post("/admin", function (req, res) {
Model.findOne({username: "siddharth"}).exec(function(err, foundList){
if(foundList)
{
const list = new linkModel({
linkTitle: req.body.linkTitle,
linkUrl: req.body.linkUrl,
});
foundList.links.push(list);
foundList.save();
res.redirect("/admin");
}
else
{res.send("redirect to home page and then login");
res.redirect("/login");
}
});
});
How can i pass the username when authenticated from login routeto other route(admin) where mongoose query is defined findone?
As i have defined it explicitly.
Or i simple terms how can i pass the data among routes ?
You can't. Instead use a middleware to do the checks you want and pass on the result to another middleware or return the response in case of error.

how to return a value or string from call back function in Nodejs, mongooose

I have a function that is inserting user credentials. I want to return value from a call back function...
var router = require('express').Router();
var User = require('../Models').users;
// function calling here
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body);
res.send(result);
});
module.exports = router;
//implemetation of function
userSchema.statics.signUp = function signUp(obj) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
return user.save(function (err, newuser) {
if (err)
{
return 'Error occured during insertion..';
} else
{
return 'You have sign up successfully...';
}
});
}
I want to return the response as a string but it showing undefined. How should it be done?
var router = require('express').Router();
var User = require('../Models').users;
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body, function(err, result){
if(err){
}
else{
res.send(result)
}
});
});
userSchema.statics.signUp = function signUp(obj, callabck) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
user.save(function (err, newuser) {
if (err)
{
callback( 'Error occured during insertion..');
} else
{
callback(null, newuser);
}
});
}
Use the callback i.e.
var router = require('express').Router();
var User = require('../Models').users;
// function calling here
router.post('/signup', function (req, res)
{
User.signUp(req.body,function(err,result){
res.send(result);
});
});
module.exports = router;
//implemetation of function
userSchema.statics.signUp = function signUp(obj,callback) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
return user.save(function (err, newuser) {
if (err)
{
callback('Error occured during insertion..',null);
} else
{
callback(null,'You have sign up successfully...');
}
});
}
Because of async nature .. Try this:
router.post('/signup', function (req, res)
{
var result = User.signUp(req.body, function(err, result){
if(err){}
else{res.send(result)}
});;
});
userSchema.statics.signUp = function signUp(obj, callabck) {
var user = new userModel(obj);
user.password = hash.generate(obj.password);
user.save(function (err, newuser) {
if (err)
{
callback( 'Error occured during insertion..',null);
} else
{
callback (null, 'You have sign up successfully...');
}
});
}

Modify req.user or use req.account?

I'm developing a mean application with passport, and I'm running through this issue:
I have a LocalStrategy to log on the user based on the application database. I need, however to login the user simultaneously on another service with possible multiple accounts. The thing is, once I route to authorize these logins, and set the variables to req.account, I cannot access them in other routes. Note that I can get the data I want, I just want to access it from somewhere other than this route, like req.user. I will post some of my code to clarify the situation.
Local Login route
app.post('/login', function (req, res, next) {
passport.authenticate('local-login', function (err, user) {
if (err)
return next(err);
if (!user)
return res.status(400).json({status: 'Invalid Username'});
req.login(user, function (err) {
if (err)
return next(err);
res.status(200).json({status: 'User successfully authenticated'});
});
})(req, res, next);
});
Local login passport config
passport.use('local-login', new LocalStrategy(function (user, pswd, done) {
User.findOne({'username': user}, function (err, user) {
if (err)
return done(err);
if (!user || !user.validPassword(pswd))
return done(null, false);
return done(null, user);
});
}));
The other service passport config
passport.use('other-login', new OtherStrategy(function (docs, done) {
if (docs.length === 0)
return done(null, false);
var accounts = [];
var user, pswd, data;
var counter = docs.length;
for (var i = 0; i < docs.length; i++) {
user = docs[i]._id;
pswd = docs[i].password;
request.post(<serviceurl>, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: qs.stringify({
grant_type: 'password',
username: user,
password: pswd,
client_id: process.env.API_KEY
})
}, function (err, res, body) {
if (err)
return done(err);
data = JSON.parse(body);
data.username = docs[docs.length - counter]._id;
accounts.push(data);
counter--;
if (counter === 0)
return done(null, accounts);
});
}
}));
Other Service route
router.get('/otherservice', passport.authorize('other-login', {}) , function (req, res) {
console.log(req.account);
res.sendStatus(200);
});
Other Service authentication (from custom Strategy)
ServiceStrategy.prototype.authenticate = function (req) {
var self = this;
var id = req.user.master_id || req.user.id;
Service.find({master_id: id}, function (err, docs){
if (err)
return self.error(err);
function verified(err, data, info) {
if (err) { return self.error(err); }
if (!data) { return self.fail(info); }
self.success(data, info);
}
try {
if (self._passReqToCallback) {
self._verify(req, docs, verified);
} else {
self._verify(docs, verified);
}
} catch (ex) {
return self.error(ex);
}
});};
I found the solution! On the User Model, I added an accounts property to store the data returned on the authorization. Then, on the authorization route, I updated the user with this info, and saved. It wasn't that hard at all.
app.post('/api/login', function (req, res, next) {
passport.authenticate('local-login', function (err, user) {
if (err)
return next(err);
if (!user)
return res.status(400).json({status: 'Invalid Username'});
req.login(user, function (err) {
if (err)
return next(err);
var id = req.user.master_id || req.user.id;
Service.findOne({master_id: id}, function (err, doc) {
if (doc == null)
res.status(200).json({
status: 'User successfully authenticated',
accounts: false
});
else
return next();
});
});
})(req, res, next);
}, passport.authorize('other-login', {}), function (req, res) {
var accounts = req.account;
var user = req.user;
user.accounts = accounts;
user.save(function (err, newUser) {
if (err)
throw err;
res.status(200).json({
status: 'User sucessfully authenticated',
accounts: true
});
})
});

Updating a object in mongoose results in loop

In my nodejs API app I have this route:
router.post('/startuserseries', function(req, res, next){
if(!req.body.username){
return res.status(400).json({message: 'Geen username'});
}
User.findOne({ 'username': req.body.username}, function(err, foundUser){
if(err)
return next(err);
if (foundUser) // check the value returned for undefined
{
foundUser.isdoingchallenges = true;
foundUser.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
}
});
});
When I call this route in postman, the request never ends.
I have tried to use PUT but also didn't work, I tried various structures of code but neither worked.
This request will not finish because it doesn't write a response command on server.
You should solve easily this problem like below:
router.post('/startuserseries', function(req, res, next){
if(!req.body.username){
return res.status(400).json({message: 'Geen username'});
}
User.findOne({ 'username': req.body.username}, function(err, foundUser){
if(err)
return next(err);
if (foundUser) // check the value returned for undefined
{
foundUser.isdoingchallenges = true;
foundUser.save(function (err) {
if(err) {
res.json(err);
}
});
}
res.send(200);
// or your specific result json object
// res.json({"error":false,"message":"completed"})
});
});

Getting out of sync server response

On a successful signup of a user I am currently seeing a mostly empty page with the text undefined. Redirecting to /app at the top.
UPDATE: I should also mention that after form submittal I am redirected to /users. So on /users I see the text mentioned above.
I think it is because of the req.redirect call being within the user.save callback but I am not sure what the fix is.
I am using mongoose for the ORM.
var User = require('../models/user');
module.exports = function(app) {
app.post('/users', function(req, res, next) {
var user = new User({
email: req.body.email,
password: req.body.password
});
user.save(function(err) {
if (err)
res.send(412, {message: err});
else
req.login(user, function(err) {
if (err !== undefined) return next(err);
res.redirect('/app', {
email: user.email,
id: user._id
});
});
});
});
};
It turns out that the req.login call has to be contained in a password.authenticate callback. The example on the site left that part out.
user.save(function(err) {
if (err)
res.send(412, {message: err});
else
passport.authenticate('local', function(err, user) {
if (err) { return next(err) }
if (!user) { return res.redirect('/login') }
req.login(user, function(err) {
if (err) { return next(err); }
return res.redirect('/app', { email:user.email, id:user._id });
});
})(req, res, next);
});

Resources