如何在所有路线中添加护照js(本地策略)
how to add passport js (local-strategy) in all routes
我将经过身份验证的护照添加到我的登录路由,但我不知道如何将其添加到其他路由。 now (req.isAuthenticated) 在登录路由中为真,但在所有其他路由中为假!!!我怎样才能将它添加到所有路由,以便当用户登录时,'req.authenticated' 对它们变为真?
login.js:
const express = require("express");
const router = express.Router();
const path = require("path");
const passport = require("passport");
const session = require("express-session");
const flash = require("express-flash");
const methodOverride = require('method-override');
const bodyParser = require('body-parser');
const { getAdmins } = require("../queries/queries");
//middlewares
router.use(flash());
router.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
})
);
router.use(passport.initialize());
router.use(passport.session());
router.use(methodOverride('_method'));
//passport
const initializePassport = require("../passport-config");
initializePassport(
passport,
async (name) => {
let users = await getAdmins();
return users.find((user) => user.name == name)},
async (id) => {
let users = await getAdmins();
return users.find((user) => user.id == id)}
);
//get metod
router.get("/", checkAuthentication, (req, res) => {
res.render(path.join(__dirname, "../public/login.ejs"), {isLogin : req.isAuthenticated});
});
//post method
router.post(
"/",
passport.authenticate("local", {
successRedirect: "/messages",
failureRedirect: '/login',
failureFlash: true,
})
);
router.delete('/logout', (req, res)=>{
req.logOut();
res.redirect('/');
})
//check req authenticated
function checkAuthentication(req, res, next) {
if (req.isAuthenticated()) {
console.log('login:yes')
return next();
}
console.log('login:no');
return next();
}
module.exports = router;
passport-config.js:
const LocalStrategy = require("passport-local").Strategy;
function initialize(passport, getUserByName, getUserById) {
const authenticateUser = async (name, password, done) => {
const user = await getUserByName(name);
if (user == null) return done(null, false, { message: "sorry! user name is not exist" });
if(password == user.password){
return done(null, user);
} else done(null, false, {message : "incorrect password"});
};
passport.use(new LocalStrategy(authenticateUser));
passport.serializeUser((user, done)=> done(null, user.id));
passport.deserializeUser((id, done)=> done(null, getUserById(id)));
}
module.exports = initialize;
为了解决这个问题,我把这段代码从login.js转移到了server.js:
//midlewares
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended : false}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
我将经过身份验证的护照添加到我的登录路由,但我不知道如何将其添加到其他路由。 now (req.isAuthenticated) 在登录路由中为真,但在所有其他路由中为假!!!我怎样才能将它添加到所有路由,以便当用户登录时,'req.authenticated' 对它们变为真?
login.js:
const express = require("express");
const router = express.Router();
const path = require("path");
const passport = require("passport");
const session = require("express-session");
const flash = require("express-flash");
const methodOverride = require('method-override');
const bodyParser = require('body-parser');
const { getAdmins } = require("../queries/queries");
//middlewares
router.use(flash());
router.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
})
);
router.use(passport.initialize());
router.use(passport.session());
router.use(methodOverride('_method'));
//passport
const initializePassport = require("../passport-config");
initializePassport(
passport,
async (name) => {
let users = await getAdmins();
return users.find((user) => user.name == name)},
async (id) => {
let users = await getAdmins();
return users.find((user) => user.id == id)}
);
//get metod
router.get("/", checkAuthentication, (req, res) => {
res.render(path.join(__dirname, "../public/login.ejs"), {isLogin : req.isAuthenticated});
});
//post method
router.post(
"/",
passport.authenticate("local", {
successRedirect: "/messages",
failureRedirect: '/login',
failureFlash: true,
})
);
router.delete('/logout', (req, res)=>{
req.logOut();
res.redirect('/');
})
//check req authenticated
function checkAuthentication(req, res, next) {
if (req.isAuthenticated()) {
console.log('login:yes')
return next();
}
console.log('login:no');
return next();
}
module.exports = router;
passport-config.js:
const LocalStrategy = require("passport-local").Strategy;
function initialize(passport, getUserByName, getUserById) {
const authenticateUser = async (name, password, done) => {
const user = await getUserByName(name);
if (user == null) return done(null, false, { message: "sorry! user name is not exist" });
if(password == user.password){
return done(null, user);
} else done(null, false, {message : "incorrect password"});
};
passport.use(new LocalStrategy(authenticateUser));
passport.serializeUser((user, done)=> done(null, user.id));
passport.deserializeUser((id, done)=> done(null, getUserById(id)));
}
module.exports = initialize;
为了解决这个问题,我把这段代码从login.js转移到了server.js:
//midlewares
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended : false}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());