使用passport.js进行身份验证错误,并进行身份验证

时间:2020-06-25 21:20:40

标签: node.js authentication passport.js express-session passport-local

我似乎总是能够将用户信息保存在数据库中,但是无法越过登录页面或注册页面进入需要身份验证的页面。它会一直工作到身份验证为止,然后返回错误Unauthorized(我相信是401)。我不确定该怎么办。我已经使用了很长时间,真的可以使用一些帮助。预先感谢。

require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
const session = require("express-session");
const passport = require("passport");
const sha1 = require('sha1');
const passportLocalMongoose = require("passport-local-mongoose");

const app = express();

app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());


mongoose.connect("mongodb://localhost:27017/db", {
    useNewUrlParser: true
});
mongoose.set("useCreateIndex", true);

const userSchema = new mongoose.Schema({
    email: String,
    password: String,
    history: Array,
    type: String
});
userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());


app.post("/cregister", function (req, res){
    User.register({
                username: req.body.username,
                type: "Customer"
            }, req.body.password, function (err, user) {
        if (err){
            console.log(err);
            res.redirect("/rlc");
        }else{
            passport.authenticate("local")(req,res,function(){
                res.redirect("/book");
            });
        }
    });
});
app.post("/clogin", function (req, res) {
    const user = new User({
        username: req.body.username,
        password: String(sha1(req.body.password))
    });
    req.login(user, function (err) {
        if (err) {
            console.log(err);
            res.redirect("/rlc");
        } else {
            passport.authenticate("local")(req, res, function () {
                res.redirect("/book");
            });
        }
    });
});

0 个答案:

没有答案