提问人:Dylan Been 提问时间:11/13/2023 最后编辑:Dylan Been 更新时间:11/14/2023 访问量:59
Passport-Remember Me TypeError:无法设置 undefined 的属性(设置“user”)
Passport-Remember Me TypeError: Cannot set properties of undefined (setting 'user')
问:
我似乎找不到导致错误的问题。该应用程序是使用 Express 在 Node.js 中构建的,问题与 Passport-Remember Me 策略有关。我的服务器在装有 MySQL 的 Google Cloud 上运行
我有的代码: 路由器代码
const express = require('express')
const router = express.Router()
const uuid = require('uuid')
const passport = require('passport')
const pool = require('../db').pool
const initializepassport = require('../passport-config').initialize
initializepassport(
passport,
email => {
return new Promise((resolve, reject) => {
const query = 'SELECT * FROM user_data WHERE email = ?'
pool.query(query, [email], (error, results) => {
if (error) {
return reject(error)
}
if (results.length === 0) {
return resolve(null)
}
return resolve(results[0])
})
})
},
id => {
return new Promise((resolve, reject) => {
const query = 'SELECT * FROM user_data WHERE id = ?'
pool.query(query, [id], (error, results) => {
if (error) {
return reject(error)
}
if (results.length === 0) {
return resolve(null)
}
return resolve(results[0])
})
})
},
)
router.get('/', checkAuthenticated, (req, res) => {
res.render('index.ejs', {name: req.user.name})
})
router.get('/login', checknonAuthenticated, (req, res) => {
res.render('login.ejs')
})
router.post('/login',
passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
function(req, res, next) {
// issue a remember me cookie if the option was checked
if (!req.body.remember_me) { return next(); }
try{
const token = uuid.v4();
// Store the token in your database and associate it with the user
//storeToken(token, req.user.id);
console.warn(`not uses probelie: ${req.user.id}`)
// Set the token as a cookie
res.cookie('rememberMeToken', token, {
maxAge: 30 * 24 * 60 * 60 * 1000,
httpOnly: true,
secure: true,
});
return next()
} catch(error){
console.error(error);
// Handle the error appropriately, e.g., send a 500 Internal Server Error
res.status(500).send('Internal Server Error');
}
},
function(req, res) {
res.redirect('/');
});
function storeToken(token, id){
const data = {token: token, userid: id}
const query = "INSERT INTO remembermetokens VALUES (?, ?)"
pool.query(query, Object.values(data), (error, results) => {
if (error) {
console.error(error);
}
})
}
Passport 配置
const LocalStragtegy = require('passport-local').Strategy;
const RememberMeStrategy = require('passport-remember-me').Strategy;
const bcrypt = require('bcrypt');
const uuid = require('uuid')
const pool = require('./db').pool
function initialize(passport, getUserByEmail, getUserById) {
const autothenticateUser = async (email, password, done) => {
const user = await getUserByEmail(email);
if (!user) {
return done(null, false, { message: 'No user with that email' });
}
try {
if (!user.password) {
return done(null, false, { message: 'User password not found' });
}
const isPasswordMatch = await bcrypt.compare(password, user.password);
if (isPasswordMatch) {
return done(null, user);
} else {
return done(null, false, { message: 'Incorrect password' });
}
} catch (error) {
return done(error);
}
}
passport.use(new LocalStragtegy({ usernameField: 'email', passwordField: 'password' }, autothenticateUser));
function storeToken(token, id, callback) {
const data = { token: token, userid: id };
const query = "INSERT INTO remembermetokens VALUES (?, ?)";
pool.query(query, Object.values(data), (error, results) => {
if (error) {
console.error(error);
callback(error);
} else {
callback(null, results); // Pass the result to the callback
}
});
}
function retrievetoken(token, callback) {
const query = 'SELECT * FROM remembermetokens WHERE token = ?';
pool.query(query, [token], (error, results) => {
if (error) {
return callback(error);
}
if (results.length === 0) {
return callback(null, null);
}
const queryd = 'DELETE * FROM remembermetokens WHERE token = ?';
pool.query(queryd, [token], (error) => {
if (error) {
return callback(error);
}
})
return callback(null, results[0].userId); // Assuming userId is a property in the result
});
}
passport.use(new RememberMeStrategy({ passReqToCallback: true },
function (user, done) {
const token = uuid.v4()
storeToken(token, user.id, function (err) {
if (err) return done(err);
return done(null, token);
});
},
function (token, done) {
retrievetoken(token, function (err, userId) {
if (err) return done(err);
if (!userId) return done(null, false);
getUserById(userId, function (err, user) {
if (err) return done(err);
return done(null, user);
});
});
}
));
passport.serializeUser(function (user, cb) {
process.nextTick(function () {
return cb(null, {
id: user.id,
email: user.email,
name: user.name,
});
});
});
passport.deserializeUser(function (user, cb) {
process.nextTick(function () {
return cb(null, user);
});
})
}
module.exports = { initialize };
服务器代码:
if(process.env.NODE_ENV !== 'production'){
require('dotenv').config()
}
const express = require('express')
const cookieParser = require('cookie-parser')
const expressLayouts = require('express-ejs-layouts')
const app = express()
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const methodOverride = require('method-override')
const indexRouter = require('./routes/index')
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'))
app.set('layout', __dirname + '/layouts/layout')
app.use(expressLayouts)
app.use(express.urlencoded({extended: false}))
app.use(cookieParser())
app.use(flash())
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(passport.authenticate('remember-me'))
app.use(methodOverride('_method'))
app.use('/', indexRouter)
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
我试图实施 Passport-Remember Me 策略,但我就是无法让它发挥作用。谁能帮忙?先谢谢你。
答: 暂无答案
评论