Reputation: 177
I'm using nodejs 8.9.3 and express 4.15.5.
What I'm doing is trying to save user information into req
at the time of logging in. After authentication is successful, I re-specify user variables. Then once that is done, when I access i.e. '/dashboard'
the user information is not stored.
What I've attempted
res.send(stuff)
to res.redirect('/dashboard')
req.session.user
instead of req.user
I've had absolutely no luck in attempting to get this to work.
app.js
...
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: 'javascript',
saveUninitialized: true,
resave: false,
rolling: false,
cookie: {
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
secure: process.env.NODE_env === 'production', // currently false as NODE_env is development atm
}
}));
...
// Load routes
require('./routes/auth.js')(app);
auth.js
let userPre = {
dn: '',
userPrincipalName: '',
sAMAccountName: '',
displayName: '',
pwdLastSet: '',
memberOf: [],
isAuthenticated: false
};
module.exports = (app) => {
let user = function(req, res, next) {
req.user = userPre;
next();
};
app.use(user);
app.get('/', (req, res) => {
res.render('login', {title: 'Login'});
});
app.post('/api/login', async(req, res) => {
await ad.user(req.body.userName).authenticate(req.body.password)
.then(async(authResponse) => {
if (authResponse === true) {
return await ad.user(req.body.userName).get();
}
else if (authResponse === false) {
res.send('failed');
return false;
}
})
.then(userProfile => {
if (!userProfile) {
return false;
} else {
req.user = {
dn: userProfile.dn,
userPrincipalName: userProfile.userPrincipalName,
sAMAccountName: userProfile.sAMAccountName,
displayName: userProfile.displayName,
pwdLastSet: userProfile.pwdLastSet,
memberOf: [],
isAuthenticated: true
};
userProfile['groups'].forEach(group => req.user.memberOf.push(group.cn));
if (req.user.memberOf.filter(obj => obj === 'Cat')) {
// authentication is successful and now I want to redirect to dashboard with req.user still being set.
// Tried req.session.save() here as well.
console.log(req.user); // Data has been set
res.redirect('/dashboard');
} else {
res.send('success') // ignore
}
}
})
.catch(err => console.log(err));
});
...
app.get('/dashboard', (req, res) => {
console.log(req.user); // all variables are still ''.
res.render('dashboard', {title: 'Dashboard'})
});
...
};
Upvotes: 0
Views: 50
Reputation: 3998
You are almost there all you have to do is store the user in the req.session.user
not on the req.user
.
req.session.user = {
dn: userProfile.dn,
userPrincipalName: userProfile.userPrincipalName,
sAMAccountName: userProfile.sAMAccountName,
displayName: userProfile.displayName,
pwdLastSet: userProfile.pwdLastSet,
memberOf: [],
isAuthenticated: true
};
Upvotes: 1