req.user未定义Express.js Passport.js

时间:2017-03-14 01:53:46

标签: javascript node.js express passport.js

下面的中间件功能无法访问req.user或检查用户是否在用户登录后登录。

我知道passport.serializeUser在登录后成功,并且在从中间件功能访问时定义了req

我是节点及其软件包的新手,所以我可能会遗漏一些基本的东西。非常感谢任何帮助。

中间件功能:

app.use('/private/*', function(req, res, next) {
    console.log(req.user); // returns undefined
    console.log(req.isAuthenticated()) // returns false
    res.redirect('/')
});

完整代码:

var express = require('express'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    bodyParser = require('body-parser'),
    flash = require('express-flash'),
    http = require('http');

var app = express()

app.use(flash());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(session({
secret: 'akdsgklasdglkadsgladsglk',
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize())
app.use(passport.session())
app.use(cookieParser('sdagahafdhfdshdfshfsd'))

// Store users
var users = {}

// Configure passport validation
function get_pass(username, password, callback) {
var params = {
          "username": username,
          "password": password,
          "app_token": 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
          "app_version": '1.0'
        }

var options = {
    hostname: 'sub_domain.domain.com',
    path: '/path/path/path/authenticate',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    }
};

var plasma_req = http.request(options, function(plasma_res) {
    if (plasma_res.statusCode === 201) {
        // Login passed
        plasma_res.setEncoding('utf8');
        let rawData = '';
        plasma_res.on('data', (chunk) => rawData += chunk);
        plasma_res.on('end', () => {
            try {
                let parsedData = JSON.parse(rawData);
                var user = {'username': parsedData['user']['username'],
                    'fname': parsedData['user']['first_name'],
                    'lname': parsedData['user']['last_name'],
                    'user_id': parsedData['user']['user_id'],
                    'email': parsedData['user']['email']
                };
                // add user to local database
                users["id" + user['user_id']] = user
                callback([true, user])
            } catch (e) {
                console.log(e.message);
            }
        });
    } else {
        // Login failed
        console.log('Failed Status: ' + plasma_res.statusCode);
        callback([false, {}])
    }
});
plasma_req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});
plasma_req.write(JSON.stringify(params));
plasma_req.end();
}

// Define passport strategy
passport.use(new LocalStrategy(
function (username, password, done) {
    status = get_pass(username, password, function(status) {
        if (status[0]) {
            console.log("Success")
            // return true
            return done(null, status[1])
        } else {
            console.log("Failure", status)
            // return false
            return done(null, false, { message: "Incorrect credentials"})
        }
    });
}
));

// Serialise user
passport.serializeUser(function (user, done) {
if (users['id' + user.user_id]) {
    done(null, 'id' + user.user_id);
} else {
    done(new Error("CANT_SERIALIZE_THIS_USER"));
}
});

// Deserialise user
passport.deserializeUser(function (userid, done) {
if (users[userid]) {
    done(null, users[userid]);
} else {
    done(new Error("THAT_USER_DOESNT_EXIST"));
}
});

// Login
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: 'login',
successFlash: {message : 'Welcome!'},
failureFalse: true
}));

app.use('/private/*', function(req, res, next) {
    console.log(req.user); // returns undefined
    console.log(req.isAuthenticated()) // returns false
    res.redirect('/')
});
app.use(express.static(__dirname + '/public'))

// Serve it up
var PORT = process.env.PORT || 3000;
app.listen(PORT, function () {
console.log('Server running @ port ' + PORT )
})

1 个答案:

答案 0 :(得分:-1)

解决了问题

var express = require('express'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
bodyParser = require('body-parser'),
flash = require('express-flash');

var app = express()

app.use(flash());
app.use(session({
    secret: 'cat_on_keyboard',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false }
}));

app.use(cookieParser('cat_on_keyboard'))
app.use(passport.initialize())
app.use(passport.session())

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

// Store users
var users = {
    "id1" : { user_id: 1, username: "admin", password: "admin"}
};

// Config passport local
passport.use(new LocalStrategy(
    function (username, password, done) {
        for (userid in users) {
            var user = users[userid];
            if (user.username.toLowerCase() == username.toLowerCase()) {
                if (user.password == password) {
                    return done(null, user)
                }
            }
        }
        return done(null, false, { message: "Incorect credentials" });
    }
));

// Serialise user
passport.serializeUser(function (user, done) {
    if (users['id' + user.user_id]) {
        done(null, 'id' + user.user_id);
    } else {
        done(new Error("CANT_SERIALIZE_THIS_USER"));
    }
});

// Deserialise user
passport.deserializeUser(function (userid, done) {
    if (users[userid]) {
        done(null, users[userid]);
    } else {
        done(new Error("THAT_USER_DOESNT_EXIST"));
    }
});

app.get('/', function (req, res) {
    console.log(req.flash());

    h_page = '<h1>Title of landing page</h1>' +
    '<a href="/login"><div style="display: inline-block; padding: 5px; margin: 10px; border-radius: 3px; border: 1px solid grey; cursor: pointer; background-color: #F8F8F8;"><span>Log In</span></div></a>' +
    '<a href="/private"><div style="display: inline-block; padding: 5px; margin: 10px; border-radius: 3px; border: 1px solid grey; cursor: pointer; background-color: #F8F8F8;"><span>Private</span></div></a>';

    res.send(h_page)
});

app.get("/login", function (req, res) {
    var error = req.flash("error");
    var form = '<!DOCTYPE html>' +
    '<html>' +
    '    <body>HTML Login form</body>' +
    '</html>';

    res.send(form);
});

// Login
app.post('/login', passport.authenticate('local', {
    successRedirect: '/private',
    failureRedirect: '/login',
    successFlash: {message : 'Welcome!'},
    failureFlash: true
}));

app.get('/private', authenticateOrNot, function(req, res) {
    console.log(req.flash('success'));
    res.end('Secrets');
});

function authenticateOrNot (req, res, next) {
    if (req.isAuthenticated()) {
        next()
    } else {
        console.log("Unathenticated user, redirecting to login");
        res.redirect('/login')
    }
}

// Serve it up
var PORT = process.env.PORT || 8080;
app.listen(PORT, function () {
    console.log('Server running @ port ' + PORT )
})