0
下面的中間件功能無法訪問req.user或檢查時用戶登錄的用戶登錄後英寸req.user未定義Express.js Passport.js
我知道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)
})