我正在尝试实施护照。我想要实现的目标是只有登录的用户才能访问/创建路线并创建新帖子。 我导入了必要的库。
import passport from "passport";
import localStrategy from "passport-local";
import session from "express-session";
import connectPgSimple from 'connect-pg-simple';
我实现了密码逻辑。
passport.use(new localStrategy(async function verify(username, password, cb) {
try {
const result = await db.query(`SELECT * FROM loginDetail WHERE username = $1`, [username]);
if (result.rows.length === 0) {
return cb(null, false, { message: "Incorrect username or password" });
}
const row = result.rows[0];
bcrypt.compare(password, row.password, (err, result) => {
if (err) {
console.error("Error comparing passwords:", err);
return cb(null, false, { message: "Failed to compare passwords" });
} else if (result) {
// Passwords match, user is authorized
return cb(null, row);
} else {
// Passwords don't match, render login page with error message
return cb(null, false, { message: "Invalid credentials. Please try again." });
}
});
} catch (err) {
return cb(err);
}
}));
app.use(
session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
cookie: { secure: true }
})
);
passport.serializeUser(function(user, cb) {
cb(null, user.id);
});
// passport.deserializeUser(function(id, cb) {
// // Retrieve user from the database based on the provided ID
// // Example assuming you have a `User` model:
// db.query('SELECT * FROM users WHERE id = $1', [id], function(err, result) {
// if (err) { return cb(err); }
// cb(null, user);
// });
// });
passport.deserializeUser(function(id, done) {
db.query('SELECT * FROM loginDetail WHERE id = $1', [id], function(err, result) {
if(err)
return done(err, user);
if(result.rows.length > 0){
const user = result.rows[0];
done(null, user)
}else{done(null, false)}
});
});
app.use(passport.initialize());
app.use(passport.session());
app.post("/login",passport.authenticate('local', { failureRedirect: '/login',successRedirect:"/" }), async (req, res) => {
});
我创建 EnsureAuthenticated 以确保只有登录用户才能访问/创建路由。
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
// If the user is authenticated, allow the request to proceed
return next();
} else {
// If the user is not authenticated, redirect to the login page
res.redirect("/login");
}
}
app.get("/create",ensureAuthenticated, (req, res) => {
res.render("create.ejs");
});
app.post("/create",ensureAuthenticated, async (req, res) => {
const result = await db.query("SELECT MAX(id) AS max_id FROM posts");
const maxId = result.rows[0].max_id || 0; // If no posts exist, set maxId to 0
// Increment the maximum ID by one to generate a new unique ID
const newId = maxId + 1;
const post = {
id: newId,
author: req.body.author,
title: req.body.title,
content: req.body.content,
};
const postPush = await db.query(
"INSERT INTO posts (id,author,title,content) VALUES($1,$2,$3,$4) RETURNING *;",
[post.id, post.author, post.title, post.content]
);
});
我实现了护照逻辑并创建了函数 EnsureAuthenticated 以仅允许登录用户访问和创建帖子。我成功登录并被重定向到/。
我解决了在 stackoverflow 上发现的问题“我的问题是我将 cookie.secure 设置为 true,即使数据未通过 https.https://stackoverflow.com/questions/29111571/passports-req-isauthenticated-always-returning -即使我硬编码完成时也为假
app.use(require('express-session')({ 秘密:process.env.sessionSecret, 曲奇饼: { maxAge: 1000 * 60 * 60 * 24 * 7 // 1周 }, 商店: 商店, 重新保存:假, 保存未初始化:假, cookie: { secure: false } // 记得设置这个 }));如果您不使用 https,请记住将 cookie 设置为 false
cookie: { secure: false } // 设置为 false 如果你相信的话 有https记得信任代理
app.set('trust proxy', 1) // 信任第一个代理"