如何在Expressjs中实施3种不同的Passport本地策略
希望你身体健康,做得很好,我正在从事旅游应用,作为我在Express js研究生学位的最后一个项目。 在那里,我不得不使用3个不同的仪表盘[博主、活动组织者和游客],用于完全不同的目的 我应该如何使用3种不同的本地策略,以便如果用户使用电子邮件和密码,那么他/她可以根据他们使用注册定义的角色重定向到他们的仪表板 我已经附加了数据库模式、控制器和App.js 目前,在成功登录后,我将呈现到名为Profile的演示页面 /****数据库模式*****/如何在Expressjs中实施3种不同的Passport本地策略,express,authentication,passport.js,dashboard,passport-local,Express,Authentication,Passport.js,Dashboard,Passport Local,希望你身体健康,做得很好,我正在从事旅游应用,作为我在Express js研究生学位的最后一个项目。 在那里,我不得不使用3个不同的仪表盘[博主、活动组织者和游客],用于完全不同的目的 我应该如何使用3种不同的本地策略,以便如果用户使用电子邮件和密码,那么他/她可以根据他们使用注册定义的角色重定向到他们的仪表板 我已经附加了数据库模式、控制器和App.js 目前,在成功登录后,我将呈现到名为Profile的演示页面 /****数据库模式*****/ const mongoose = re
const mongoose = require ("mongoose");
const userSchema=new mongoose.Schema({
fname:{
type:"String",
},
lname:{
type:"String"
},
username:{
type:"String",
unique:true
},
email:{
type:"String",
unique:true,
},contact:{
type:"String",
unique:true,
},
roleperson:{
type:"String"
},
gender:{
type:"String"
},
password:{
type:"String"
},
cpassword:{
type:"String"
},
isVerified: {
type: Boolean,
default: false,
},
googleId: {
type: String,
},
provider: {
type: String,
required: true,
}
})
// Model i.e Collection creation should be
const user =new mongoose.model("User", userSchema);
module.exports=user;
/****Passportjs控制器*****/
const user = require('../model/user');
const bcryptjs = require('bcryptjs');
var localStrategy = require('passport-local').Strategy;
module.exports = function (passport) {
passport.use(new localStrategy({ usernameField: 'email' }, (email, password, done) => {
user.findOne({ email: email }, (err, data) => {
if (err) throw err;
if (!data) {
return done(null, false, { message: "User Doesn't Exist !" });
}
bcryptjs.compare(password, data.password, (err, match) => {
if (err) {
return done(null, false);
}
if (!match) {
return done(null, false, { message: "Password Doesn't match !" });
}
if (match) {
return done(null, data);
}
})
})
}));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
user.findById(id, function (err, user) {
done(err, user);
});
});
}
const express = require('express');
const router = express.Router();
const bcryptjs = require('bcryptjs');
const passport = require('passport');
require('./passportLocal')(passport);
require('./googleAuth')(passport);
const userRoutes = require('./accountRoutes');
const path=require('path')
const static_path = path.join(__dirname, '../../public')
function checkAuth(req, res, next) {
if (req.isAuthenticated()) {
res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, post-check=0, pre-check=0');
next();
} else {
req.flash('error_messages', "Please Login to continue !");
res.redirect('/login');
}
}
// Getting the collection of DB
const NewsletterSubsciber = require('../model/newsletter')
const ContactUs_Client = require("../model/contactus")
const user =require('../model/user')
router.post('/signup', (req, res) => {
// get all the values
const {fname,lname,gender,roleperson,email,contact, username, password, cpassword } = req.body;
// check if the are empty
if (!fname || !lname || !gender || !roleperson || !email ||!contact || ! username || !password || !cpassword) {
res.render("signup", { err: "All Fields Required !" });
} else if (password != cpassword) {
res.render("signup", { err: "Password Don't Match !" });}
else if (password.length<8) {
res.render("signup", { err: "Password Must be atleast 8 charchter!" });
} else {
// validate email and username and password
// skipping validation
// check if a user exists
user.findOne({ $or: [{ email: email }, { username: username },{ contact: contact }] }, function (err, data) {
if (err) throw err;
if (data) {
res.render("signup", { err: "User already Exists, Try Logging In !" });
} else {
// generate a salt
bcryptjs.genSalt(12, (err, salt) => {
if (err) throw err;
// hash the password
bcryptjs.hash(password, salt, (err, hash) => {
if (err) throw err;
// save user in db
user({
fname:fname,
lname:lname,
gender:gender,
roleperson:roleperson,
username: username,
contact: contact,
email: email,
password: hash,
googleId: null,
provider: 'email',
}).save((err, data) => {
if (err) throw err;
// login the user
// use req.login
// redirect , if you don't want to login
res.redirect('/login');
});
})
});
}
});
}
});
router.post('/login', (req, res, next) => {
passport.authenticate('local', {
failureRedirect: '/login',
successRedirect: '/profile',
failureFlash: true,
})(req, res, next);
});
router.get('/logout', (req, res) => {
req.logout();
req.session.destroy(function (err) {
res.redirect('/');
});
});
// Authenication Form Google but that is ignore in Our Project
router.get('/google', passport.authenticate('google', { scope: ['profile', 'email',] }));
router.get('/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => {
res.redirect('/profile');
});
router.post('/index', async (req, res) => {
try {
const newlettersubsciber = new NewsletterSubsciber({
email: req.body.email,
})
const dataenter = await newlettersubsciber.save();
res.status(201).render("index",{ err: "Request is Send Succesfully"});
} catch (error) {
res.sendStatus(400).send(error)
console.log(`The Error is:${error}`)
}
})
router.post('/contact', async (req, res) => {
try {
const contact_client = new ContactUs_Client({
name: req.body.name,
email: req.body.email,
textaera: req.body.textaera,
phone: req.body.phone,
})
const dataenter = await contact_client.save();
res.status(201).render("index");
} catch (error) {
res.sendStatus(400).send(error)
console.log(`The Error is:${error}`)
}
})
router.get('/profile', checkAuth, (req, res) => {
// adding a new parameter for checking verification
res.render('profile', { username: req.user.username, verified : req.user.isVerified });
});
// All static Pages Of Website
router.get('/', (req, res) => {
if (req.isAuthenticated()) {
res.render("index", { logged: true });
} else {
res.render("index", { logged: false });
}
});
router.get('/login', (req, res) => {
res.render("login");
});
router.get('/signup', (req, res) => {
res.render("signup");
});
router.get('/contact', (req, res) => {
res.render("contact")
})
router.get('/findevent', (req, res) => {
res.render("FindEvent")
})
router.get('/blogs', (req, res) => {
res.render("Blogs")
})
router.use('/about', (req, res) => {
res.sendFile(static_path + "/pages/About.html")
})
router.use('/rentaroom', (req, res) => {
res.sendFile(static_path + "/pages/Rentaroom.html")
})
router.use('/touristguider', (req, res) => {
res.sendFile(static_path + "/pages/touristguider.html")
})
router.use('/eventorganizerpolicy', (req, res) => {
res.sendFile(static_path + "/pages/event_org_policy.html")
})
router.use('/bloggerpolicy', (req, res) => {
res.sendFile(static_path + "/pages/Blogger_policy.html")
})
router.use('/touristpolicy', (req, res) => {
res.sendFile(static_path + "/pages/Tourist_policy.html")
})
router.use('/touristguiderpolicy', (req, res) => {
res.sendFile(static_path + "/pages/TouristGuider_policy.html")
})
router.use('/privacypolicy', (req, res) => {
res.sendFile(static_path + "/pages/Privacy_Policy.html")
})
router.use('/safteypolicy', (req, res) => {
res.sendFile(static_path + "/pages/Safety_Policy.html")
})
router.use('/copywritepolicy', (req, res) => {
res.sendFile(static_path + "/pages/Copywrite_policy.html")
})
router.use('/tod', (req, res) => {
res.sendFile(static_path + "/pages/TOD.html")
})
router.use('/faqs', (req, res) => {
res.sendFile(static_path + "/pages/FAQS.html")
})
// BloggerDashboard Routes
router.get('/bloggerdashboard', function (req, res) {
res.render('blogger_dash/index', {});
})
router.get('/bloggerdashboard/addnewpost', function (req, res) {
res.render('blogger_dash/add-new-post', {});
})
router.get('/bloggerdashboard/auduience', function (req, res) {
res.render('blogger_dash/auduience', {});
})
router.get('/bloggerdashboard/blogspost', function (req, res) {
res.render('blogger_dash/components-blog-posts', {});
})
router.get('/bloggerdashboard/userprofile', function (req, res) {
res.render('blogger_dash/user-profile-lite', {});
})
// Event Org Dashboard Routes
router.get('/eventorgdashboard', function (req, res) {
res.render('eventOrg_dash/index', {});
})
router.get('/eventorgdashboard/create_event', function (req, res) {
res.render('eventOrg_dash/create_an_event', {});
})
router.get('/eventorgdashboard/invoicelist', function (req, res) {
res.render('eventOrg_dash/invoicelist', {});
})
router.get('/eventorgdashboard/profile', function (req, res) {
res.render('eventOrg_dash/profile', {});
})
router.get('/eventorgdashboard/userlist', function (req, res) {
res.render('eventOrg_dash/userlist', {});
})
//Tourist Org Dashboard Routes
router.get('/touristdashboard', function (req, res) {
res.render('tourist_dash/index', {});
})
router.get('/touristdashboard/previousevent', function (req, res) {
res.render('tourist_dash/previousevent', {});
})
router.get('/touristdashboard/touristprofile', function (req, res) {
res.render('tourist_dash/touristprofile', {});
})
router.use(userRoutes);
module.exports = router;
/****路由器控制器*****/
const user = require('../model/user');
const bcryptjs = require('bcryptjs');
var localStrategy = require('passport-local').Strategy;
module.exports = function (passport) {
passport.use(new localStrategy({ usernameField: 'email' }, (email, password, done) => {
user.findOne({ email: email }, (err, data) => {
if (err) throw err;
if (!data) {
return done(null, false, { message: "User Doesn't Exist !" });
}
bcryptjs.compare(password, data.password, (err, match) => {
if (err) {
return done(null, false);
}
if (!match) {
return done(null, false, { message: "Password Doesn't match !" });
}
if (match) {
return done(null, data);
}
})
})
}));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
user.findById(id, function (err, user) {
done(err, user);
});
});
}
const express = require('express');
const router = express.Router();
const bcryptjs = require('bcryptjs');
const passport = require('passport');
require('./passportLocal')(passport);
require('./googleAuth')(passport);
const userRoutes = require('./accountRoutes');
const path=require('path')
const static_path = path.join(__dirname, '../../public')
function checkAuth(req, res, next) {
if (req.isAuthenticated()) {
res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, post-check=0, pre-check=0');
next();
} else {
req.flash('error_messages', "Please Login to continue !");
res.redirect('/login');
}
}
// Getting the collection of DB
const NewsletterSubsciber = require('../model/newsletter')
const ContactUs_Client = require("../model/contactus")
const user =require('../model/user')
router.post('/signup', (req, res) => {
// get all the values
const {fname,lname,gender,roleperson,email,contact, username, password, cpassword } = req.body;
// check if the are empty
if (!fname || !lname || !gender || !roleperson || !email ||!contact || ! username || !password || !cpassword) {
res.render("signup", { err: "All Fields Required !" });
} else if (password != cpassword) {
res.render("signup", { err: "Password Don't Match !" });}
else if (password.length<8) {
res.render("signup", { err: "Password Must be atleast 8 charchter!" });
} else {
// validate email and username and password
// skipping validation
// check if a user exists
user.findOne({ $or: [{ email: email }, { username: username },{ contact: contact }] }, function (err, data) {
if (err) throw err;
if (data) {
res.render("signup", { err: "User already Exists, Try Logging In !" });
} else {
// generate a salt
bcryptjs.genSalt(12, (err, salt) => {
if (err) throw err;
// hash the password
bcryptjs.hash(password, salt, (err, hash) => {
if (err) throw err;
// save user in db
user({
fname:fname,
lname:lname,
gender:gender,
roleperson:roleperson,
username: username,
contact: contact,
email: email,
password: hash,
googleId: null,
provider: 'email',
}).save((err, data) => {
if (err) throw err;
// login the user
// use req.login
// redirect , if you don't want to login
res.redirect('/login');
});
})
});
}
});
}
});
router.post('/login', (req, res, next) => {
passport.authenticate('local', {
failureRedirect: '/login',
successRedirect: '/profile',
failureFlash: true,
})(req, res, next);
});
router.get('/logout', (req, res) => {
req.logout();
req.session.destroy(function (err) {
res.redirect('/');
});
});
// Authenication Form Google but that is ignore in Our Project
router.get('/google', passport.authenticate('google', { scope: ['profile', 'email',] }));
router.get('/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => {
res.redirect('/profile');
});
router.post('/index', async (req, res) => {
try {
const newlettersubsciber = new NewsletterSubsciber({
email: req.body.email,
})
const dataenter = await newlettersubsciber.save();
res.status(201).render("index",{ err: "Request is Send Succesfully"});
} catch (error) {
res.sendStatus(400).send(error)
console.log(`The Error is:${error}`)
}
})
router.post('/contact', async (req, res) => {
try {
const contact_client = new ContactUs_Client({
name: req.body.name,
email: req.body.email,
textaera: req.body.textaera,
phone: req.body.phone,
})
const dataenter = await contact_client.save();
res.status(201).render("index");
} catch (error) {
res.sendStatus(400).send(error)
console.log(`The Error is:${error}`)
}
})
router.get('/profile', checkAuth, (req, res) => {
// adding a new parameter for checking verification
res.render('profile', { username: req.user.username, verified : req.user.isVerified });
});
// All static Pages Of Website
router.get('/', (req, res) => {
if (req.isAuthenticated()) {
res.render("index", { logged: true });
} else {
res.render("index", { logged: false });
}
});
router.get('/login', (req, res) => {
res.render("login");
});
router.get('/signup', (req, res) => {
res.render("signup");
});
router.get('/contact', (req, res) => {
res.render("contact")
})
router.get('/findevent', (req, res) => {
res.render("FindEvent")
})
router.get('/blogs', (req, res) => {
res.render("Blogs")
})
router.use('/about', (req, res) => {
res.sendFile(static_path + "/pages/About.html")
})
router.use('/rentaroom', (req, res) => {
res.sendFile(static_path + "/pages/Rentaroom.html")
})
router.use('/touristguider', (req, res) => {
res.sendFile(static_path + "/pages/touristguider.html")
})
router.use('/eventorganizerpolicy', (req, res) => {
res.sendFile(static_path + "/pages/event_org_policy.html")
})
router.use('/bloggerpolicy', (req, res) => {
res.sendFile(static_path + "/pages/Blogger_policy.html")
})
router.use('/touristpolicy', (req, res) => {
res.sendFile(static_path + "/pages/Tourist_policy.html")
})
router.use('/touristguiderpolicy', (req, res) => {
res.sendFile(static_path + "/pages/TouristGuider_policy.html")
})
router.use('/privacypolicy', (req, res) => {
res.sendFile(static_path + "/pages/Privacy_Policy.html")
})
router.use('/safteypolicy', (req, res) => {
res.sendFile(static_path + "/pages/Safety_Policy.html")
})
router.use('/copywritepolicy', (req, res) => {
res.sendFile(static_path + "/pages/Copywrite_policy.html")
})
router.use('/tod', (req, res) => {
res.sendFile(static_path + "/pages/TOD.html")
})
router.use('/faqs', (req, res) => {
res.sendFile(static_path + "/pages/FAQS.html")
})
// BloggerDashboard Routes
router.get('/bloggerdashboard', function (req, res) {
res.render('blogger_dash/index', {});
})
router.get('/bloggerdashboard/addnewpost', function (req, res) {
res.render('blogger_dash/add-new-post', {});
})
router.get('/bloggerdashboard/auduience', function (req, res) {
res.render('blogger_dash/auduience', {});
})
router.get('/bloggerdashboard/blogspost', function (req, res) {
res.render('blogger_dash/components-blog-posts', {});
})
router.get('/bloggerdashboard/userprofile', function (req, res) {
res.render('blogger_dash/user-profile-lite', {});
})
// Event Org Dashboard Routes
router.get('/eventorgdashboard', function (req, res) {
res.render('eventOrg_dash/index', {});
})
router.get('/eventorgdashboard/create_event', function (req, res) {
res.render('eventOrg_dash/create_an_event', {});
})
router.get('/eventorgdashboard/invoicelist', function (req, res) {
res.render('eventOrg_dash/invoicelist', {});
})
router.get('/eventorgdashboard/profile', function (req, res) {
res.render('eventOrg_dash/profile', {});
})
router.get('/eventorgdashboard/userlist', function (req, res) {
res.render('eventOrg_dash/userlist', {});
})
//Tourist Org Dashboard Routes
router.get('/touristdashboard', function (req, res) {
res.render('tourist_dash/index', {});
})
router.get('/touristdashboard/previousevent', function (req, res) {
res.render('tourist_dash/previousevent', {});
})
router.get('/touristdashboard/touristprofile', function (req, res) {
res.render('tourist_dash/touristprofile', {});
})
router.use(userRoutes);
module.exports = router;
const express=require('express');
const router=express.router();
const bcryptjs=require('bcryptjs');
const passport=require(‘passport’);
要求(“./passportLocal”)(护照);
要求(“./googleAuth”)(护照);
const userRoutes=require('./accountRoutes');
const path=require('路径')
常量static_path=path.join(_dirname,'../../public'))
函数checkAuth(req、res、next){
如果(请求isAuthenticated()){
res.set('Cache-Control','no-Cache,private,no-store,必须重新验证,后检查=0,前检查=0');
next();
}否则{
req.flash('错误消息',“请登录以继续!”);
res.redirect('/login');
}
}
//获取数据库的集合
const newsletter subsciber=require(“../model/newsletter”)
const ContactUs_Client=require(“../model/ContactUs”)
const user=require(“../model/user”)
路由器.post('/signup',(请求、回复)=>{
//获取所有值
const{fname,lname,gender,roleperson,email,contact,username,password,cpassword}=req.body;
//请检查这些文件是否为空
如果(!fname | | |!lname | |!性别| |!角色扮演者| |!电子邮件| |!联系| |!用户名| |!密码| |!cpassword){
res.render(“注册”{err:“需要所有字段!”});
}else if(密码!=cpassword){
res.render(“注册”{err:“密码不匹配!”});}
else if(password.length{
如果(错误)抛出错误;
//散列密码
bcryptjs.hash(密码,salt,(err,hash)=>{
如果(错误)抛出错误;
//在数据库中保存用户
使用者({
fname:fname,
lname:lname,
性别:性别,,
角色扮演者:角色扮演者,
用户名:用户名,
联系人:联系人,
电邮:电邮,,
密码:hash,
googleId:null,
提供者:“电子邮件”,
}).保存((错误,数据)=>{
如果(错误)抛出错误;
//登录用户
//使用req.login
//重定向,如果您不想登录
res.redirect('/login');
});
})
});
}
});
}
});
router.post('/login',(req,res,next)=>{
passport.authenticate('local'{
failureRedirect:“/login”,
successRedirect:“/profile”,
failureFlash:没错,
})(req、res、next);
});
路由器.get('/logout',(req,res)=>{
请求注销();
请求会话销毁(功能(错误){
res.redirect('/');
});
});
//来自谷歌的授权,但这在我们的项目中被忽略
get('/google',passport.authenticate('google',{scope:['profile','email',]}));
router.get('/google/callback',passport.authenticate('google',{failureRedirect:'/login'}),(req,res)=>{
res.redirect('/profile');
});
路由器.post('/index',异步(req,res)=>{
试一试{
const newlettersubsciber=新时事通讯subsciber({
电子邮件:req.body.email,
})
const dataenter=wait newlettersubsciber.save();
res.status(201).render(“索引”{err:“请求成功发送”});
}捕获(错误){
res.sendStatus(400).send(错误)
log(`错误为:${Error}`)
}
})
路由器.post('/contact',异步(req,res)=>{
试一试{
const contact_client=新contact_client({
名称:req.body.name,
电子邮件:req.body.email,
textaera:req.body.textaera,
电话:req.body.phone,
})
const dataenter=wait contact_client.save();
res.status(201)。呈现(“索引”);
}捕获(错误){
res.sendStatus(400).send(错误)
log(`错误为:${Error}`)
}
})
路由器.get('/profile',checkAuth,(req,res)=>{
//添加用于检查验证的新参数
res.render('profile',{username:req.user.username,verified:req.user.isVerified});
});
//网站的所有静态页面
路由器.get(“/”,(请求,res)=>{
如果(请求isAuthenticated()){
res.render(“索引”{logged:true});
}否则{
res.render(“索引”{logged:false});
}
});
路由器.get('/login',(req,res)=>{
res.render(“登录”);
});
路由器.get('/signup',(req,res)=>{
res.render(“注册”);
});
路由器.get('/contact',(req,res)=>{
res.render(“联系”)
})
路由器.get('/findevent',(req,res)=>{
res.render(“FindEvent”)
})
路由器.get('/blogs',(req,res)=>{
res.render(“博客”)
})
路由器。使用('/about',(req,res)=>{
res.sendFile(静态路径+“/pages/About.html”)
})
路由器。使用('/rentaroom',(请求,res)=>{
res.sendFile(静态路径+“/pages/Rentaroom.html”)
})
路由器。使用('/touristguider',(请求、回复)=>{
res.sendFile(静态路径+“/pages/touristguider.html”)
})
路由器。使用(“/eventorganizerpolicy”,(req,res)=>{
res.sendFile(static\u path+“/pages/event\u org\u policy.html”)
})
路由器。使用(“/bloggerpolicy”,(请求、回复)=>{