I built a nodejs rest service and I want to setup an auth system. The rest services is accessed by ajax calls from
$.get("http://localhost:3000/user",{},function(data){console.log(data)});
The login is made or either an ajax call or either a direct call from the browser and neither way I can stick with sessions or cookies.
If I get a login success, the next call
$.get("http://localhost:3000/user",{},function(data){console.log(data)});
the server doesn't know who I am.
nodejs file
app.post('/login', function (req, res) {
if ('undefined' === typeof req.body.password || 'undefined' === typeof req.body.user) {
res.redirect(req.headers.referer + '?error=-2');
return;
}
mysql = tools.mysql();
var user = req.body.user,
password = crypto.createHash('md5').update(req.body.password).digest("hex"),
result = {
result: 0
},
check,
id,
value;
mysql.query('SELECT id, level, nome FROM chaves_proatlantico.utilizadores WHERE email = ? and password = ?;', [user, password])
.on('result', function (rows) {
check = crypto.createHash('md5').update(req.socket.remoteAddress + '' + Date.now()).digest("hex");
id = crypto.createHash('md5').update(user + password).digest("hex");
value = {
id: id,
check: check
};
req.session.user = rows.id;
req.session.level = rows.level;
req.session.name = rows.nome;
req.session.id = id;
req.session.check = check;
result.result = 1;
res.cookie('restid', JSON.stringify(value), { maxAge: 900000, httpOnly: false });
mysql.query('UPDATE chaves_proatlantico.utilizadores SET code = ? WHERE email = ? and password = ?;', [check, user, password]).on('end', function () {
tools.mysqlend();
})
.on('end', function () {
tools.mysqlend();
res.redirect(req.headers.referer + '?id=' + id + '&check=' + check);
})
.on('error', function (err) {
result = {result: -1, data: err.code};
});
})
.on('end', function () {
if (1 !== result.result) {
tools.mysqlend();
res.redirect(req.headers.referer + '?error=' + result.result);
}
})
.on('error', function (err) {
result = {result: -1, data: err.code};
});
});
app.get('/user', tools.requiredLogin, function (req, res) {
var result = {
result: 1,
data: {
name: req.session.name
}
};
tools.json(req, res, result);
});