您不会相信我,在尝试使用已有的bcrypt代码实施护照时,我尝试了许多事情,而今天已经将近15个小时,阅读文档并尝试了其他尝试,基本上我折磨了自己。
请任何人查看我的项目以及我将在此处发布的几个代码,但是请帮助我,我希望将护照与我拥有的bcrypt代码结合起来,我知道某些代码将被删除,而另一些代码将被添加这是正常的法律,但是请任何人 这些代码将使您深入了解事物的外观,但是请花点时间在GitHub THAAANKS <3
上浏览我的项目。https://github.com/tigerabrodi/blogcms
身份验证控制器
const path = require('path');
const bcrypt = require("bcryptjs");
const User = require("../models/user");
function getErrorMessage(req) {
let message = req.flash("error");
if (message.length > 0) {
message = message[0];
} else {
message = null;
}
return message;
}
exports.getLoginPage = (req, res) => {
res.render("blog/login", {
pageTitle: "login",
path: "/login",
errorMessage: getErrorMessage(req)
});
}
exports.getsignUpPage = (req, res) => {
res.render("blog/signup", {
pageTitle: "signup",
path: "/signup",
errorMessage: getErrorMessage(req)
});
}
exports.postLogin = async (req, res, next) => {
const {
username,
password
} = req.body;
try {
const user = await User.findOne({
username
})
if (!user) {
req.flash("error", "Invalid Email or Password.");
res.redirect("/login");
}
const correctCredentials = await bcrypt.compare(password, user.password)
if (!correctCredentials) {
req.flash("error", "Invalid Email or Password.");
res.redirect("/login");
}
req.session.isLoggedIn = true;
req.session.user = user;
const result = await req.session.save(err => {
if (err) throw err;
res.redirect("/");
});
} catch (err) {
console.log(err);
return req.flash("error", "Invalid Email or Password.");
res.redirect("/login");
}
}
exports.postLogout = (req, res, next) => {
req.session.destroy(err => {
if (err) throw err;
res.redirect("/");
})
}
exports.postSignup = (req, res, next) => {
const {
username,
password
} = req.body;
const user = new User({
username,
password
});
User.findOne({
username
}, (err, userExists) => {
if (err) return next(err);
if (userExists) {
req.flash("error", "Email exists already, please pick a different one.");
return res.redirect("/signup");
}
user.save(error => {
if (error) return next(error);
res.redirect("/login");
});
});
};
用户模型
const mongoose = require("mongoose"),
Schema = mongoose.Schema,
bcrypt = require("bcryptjs");
const userSchema = new Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true
}
});
userSchema.pre("save", async function save(next) {
const user = this;
if (!user.isModified("password")) return next();
const hashedPassword = await bcrypt.hash(user.password, 10);
user.password = hashedPassword;
next();
});
module.exports = mongoose.model("User", userSchema);
app.js
require('dotenv').config({path: "node.env"});
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const flash = require("connect-flash");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const errorController = require('./controllers/error');
const mongodb_uri = process.env.MONGODB_URI;
const app = express();
const csrf = require("csurf");
const User = require("./models/user");
const store = new MongoDBStore({
uri: mongodb_uri,
collection: "sessions"
});
const csrfProtection = csrf();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminRoutes = require("./routes/admin");
const blogRoutes = require("./routes/blog");
const authRoutes = require("./routes/auth");
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(
session({
secret: process.env.SECRET,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7
},
store: store,
resave: false,
saveUninitialized: false,
})
);
app.use(flash());
app.use(csrfProtection);
app.use((req, res, next) => {
if (!req.session.user) {
return next();
}
User.findById(req.session.user._id)
.then(user => {
if (!user) {
return next();
}
req.user = user;
next();
})
.catch(err => console.log(err));
});
app.use((req, res, next) => {
res.locals.isAuthenticated = req.session.isLoggedIn;
res.locals.csrfToken = req.csrfToken();
next();
});
app.use(adminRoutes);
app.use(blogRoutes);
app.use(authRoutes);
app.use(errorController.get404);
mongoose.set('useCreateIndex', true);
mongoose.connect(mongodb_uri, {
useNewUrlParser: true
});
app.listen(3000, function () {
console.log("listening to port 3000")
})
答案 0 :(得分:0)
在将用户插入数据库之前,您需要先哈希密码 。
您可以在postSignup
函数中执行以下操作:
exports.postSignup = (req, res, next) => {
const {
username,
password
} = req.body;
User.findOne({
username
}, (err, userExists) => {
if (err) return next(err);
if (userExists) {
req.flash("error", "Email exists already, please pick a different one.");
return res.redirect("/signup");
}
bcrypt.hash(password, 10).then((hashed) =>{
const user = {
username,
hashed
};
User.insert(user);
});
});
};
然后,当用户登录时,您需要将哈希密码与用户键入的密码进行比较。但是我看到您已经使用const correctCredentials = await bcrypt.compare(password, user.password)
进行了此操作。