如何使用已有的 bcrypt 代码实施护照?
Posted
技术标签:
【中文标题】如何使用已有的 bcrypt 代码实施护照?【英文标题】:How can I implement passport with the bcrypt code I already have? 【发布时间】:2019-11-05 06:25:07 【问题描述】:你不会相信我,在尝试使用我已经拥有的 bcrypt 代码实现护照时,我尝试了很多东西,今天将近 15 个小时,阅读文档并尝试不同的东西,基本上我在折磨自己。
请任何人查看我的项目和我将在此处发布的几个代码,但请帮助我,我很想将护照与我拥有的 bcrypt 代码结合起来,我知道一些代码将被删除并添加一些这是正常的法律,但请任何人 HEEEELP 这些代码会让您深入了解事物的外观,但请花点时间在我的 GitHub 上查看我的项目 THAAANKS
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")
)
【问题讨论】:
【参考方案1】:您需要在将用户插入数据库之前对密码进行哈希处理。
您可以在 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)
这样做了。
【讨论】:
以上是关于如何使用已有的 bcrypt 代码实施护照?的主要内容,如果未能解决你的问题,请参考以下文章
使用promisy重构护照本地策略。 .catch()的问题
您如何(如果可能)使用以下代码在网站中实现 Bcrypt 和 JWT?