for a test project I need to login with an user defined only by username, and load new page with that user. My code in the tamplate is:
<form action="/login" method="post">
username: <input type="text" name="username"><br>
password: <input type="password" name="password">
<button type="submit" style="float: right;">Login..</button>
</form>
The Express code in app.js is:
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.use(function (req, res, next) {
req.usersession = { "userId" : "myUser" };
next();
})
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//routes
app.get('/project', routes.project);
app.get('/dashboard', routes.dashboard);
app.get('/', routes.index);
app.post('/addProject', routes.addProject);
app.post('/login', routes.login);
and the /login function:
exports.login = function (req, res) {
var query = req.body.username;
Users.
findOne({ 'username' : query }).
exec(function (err, result) {
if (err) res.send('Username not found');
// exports.dashboard();
req.usersession = result._id;
});
the /dashboard
exports.dashboard = function (req, res) {
Project.
find( { "project._addedBy" : req.usersession.userId}).
select("project.projectName project._addedBy").
exec(function (err, result) {
if (err) throw err;
var data = { "rendData" : result };
res.render('dashboard', data);
});
};
When the browser is redirected to /dashboard, it starts with the initial data for req.usersession - myUser. How could I pass the req.usersession between both pageloads?
Sorry if my terms are not right, but I am new to the web.
Thanks!
I believe the problem is that you are mixing the approaches. The middleware app.use function logs in a fake user and it does that for every request. You are then trying to do an actual login by checking the database for the form data. The middleware will override the actual login for every other request. You should pick one or the other - a real login with a db check and a session or a mock login middleware if you don't care to go all the way for this study project...