1

我建立了一个 nodejs 休息服务,我想设置一个身份验证系统。其余服务由来自的 ajax 调用访问

$.get("http://localhost:3000/user",{},function(data){console.log(data)});

登录或ajax调用或来自浏览器的直接调用,我无法坚持使用会话或cookie。

如果我登录成功,下一次调用

$.get("http://localhost:3000/user",{},function(data){console.log(data)});

服务器不知道我是谁。

node.js 文件

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);
    });
4

0 回答 0