Я пытаюсь создать систему входа в систему для двух пользователей: один - администратор, а второй - доктор. Здесь я создаю промежуточное программное обеспечение, которое отлично работает для первого, т.е. администратора, но в случае доктора оно снова и снова перенаправляет меня на страницу входа, хотя мой пароль и имя пользователя верны.
пожалуйста, кто-нибудь, дайте мне знать, как создать промежуточное программное обеспечение для двух моделей аутентификации
'use strict';
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
mongoose = require('mongoose');
var Admin = require("./models/admin");
var Doctor = require("./models/doctor");
var http = require('http');
var port = process.env.PORT || 1337;
//Set up default mongoose connection
var mongoDB = 'mongodb://localhost:27017/seeddb';
mongoose.connect(mongoDB, { useNewUrlParser: true });
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public", { redirect: false }));
//PASSPORT CONFIGURTION
app.use(require("express-session")({
secret: "Rockey is the best",`enter code here`
resave: false,
saveUninitialized: false,
}));
app.enable('trust proxy');
app.use(passport.initialize());
app.use(passport.session());
app.use(require('flash')());
//=========================================================
//Admin Authentication
passport.use('adminLocal', new LocalStrategy(Admin.authenticate()));
passport.serializeUser(Admin.serializeUser());
passport.deserializeUser(Admin.deserializeUser());
//Doctor Authentication
passport.use('doctorLocal', new LocalStrategy(Doctor.authenticate()));
passport.serializeUser(Doctor.serializeUser());
passport.deserializeUser(Doctor.deserializeUser());
//=========================================================
app.use(function (req, res, next) { // to pass currentUser to each routes
res.locals.currentUser = req.user;
next();
});
//========================================================
//Landing route
//========================================================
app.get('/', function (req, res) {
res.render("clinic/landing");
});
//=========================================================
//Admin routes
//=========================================================
app.get('/admin-login', function (req, res) {
res.render("admin/login");
});
//Sign Up
app.post('/admin-signup', function (req, res) {
var newAdmin = new Admin({ username: req.body.username });
Admin.register(newAdmin, req.body.password, function (err, admin) {
if (err) {
console.log(err);
return res.redirect("/admin-login");
}
passport.authenticate("adminLocal")(req, res, function () { //local can be twitter fb for authentication
console.log("Successfully signup Login to continue");
res.redirect("/admin-login");
});
});
});
//Admin sign in
// process the login form
app.post('/admin-login', function (req, res, next) {
passport.authenticate('adminLocal', { failureFlash: true }, function (err, admin, info) {
if (err) { return next(err); }
if (!admin) { return res.redirect('/admin-login'); }
req.logIn(admin, function (err) {
if (err) { return next(err); }
return res.redirect('/admin/' + admin._id);
});
})(req, res, next);
});
//Admin home
app.get('/admin/:id', isLoggedIn, function (req, res) {
Admin.findById(req.params.id, function (err, admin) {
if (err) {
console.log(err);
} else {
Doctor.find({}).exec(function (err, doctors) {
if (err) throw err;
res.render("admin/adminhome", {"doctors" : doctors, admin: admin });
});
}
});
});
//===============================================
//Doctor routes
//===============================================
//Doctor login
app.get('/doctor-login', function (req, res) {
Admin.findById(req.params.id, function (err, admin) {
if (err) {
console.log(err);
} else {
res.render("doctors/login");
}
});
});
app.post('/doctor-signup', function (req, res) {
var newDoctor = new Doctor({
username: req.body.username,
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
exp: req.body.exp,
dept: req.body.dept,
address: req.body.address,
hospInfo: req.body.hospInfo,
desc: req.body.description,
});
Doctor.register(newDoctor, req.body.password, function (err, doctor) {
if (err) {
console.log(err);
return res.redirect("back");
}
passport.authenticate("doctorLocal")(req, res, function (){ //local can be twitter fb for authentication
console.log("Doctor signup successfully Done");
res.redirect("/doctor-login");
});
});
});
//Doctor sign in
// process the login form
app.post('/doctor-login', function (req, res, next) {
passport.authenticate('doctorLocal', { failureFlash: true }, function (err, doctor, info) {
if (err) { return next(err); }
if (!doctor) { console.log("No doc found"); return res.redirect('/doctor-login'); }
req.logIn(doctor, function (err) {
if (err) { return next(err); }
return res.redirect('/doctor/' + doctor._id);
});
})(req, res, next);
});
//doctor home
app.get('/doctor/:id', isLoggedIn, function (req, res) {
Doctor.findById(req.params.id, function (err, doctor) {
if (err) {
console.log(err);
} else {
res.render("doctors/doctorhome", { doctor: doctor });
}
});
});
// //middleware to check whether it is logged in or not
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect("back");
}