gpt4 book ai didi

mongodb - 在 node.js 和 mongodb 中创建注册和登录表单

转载 作者:IT老高 更新时间:2023-10-28 11:03:23 28 4
gpt4 key购买 nike

我是 node.js 的新手,想为用户创建一个注册和登录页面。还必须对用户进行适当的授权。我想将用户信息存储在 mongodb 数据库中。我怎样才能实现这一点。可以有人为我提供了这样做的代码,以便我可以开始使用 node.js 和 mongodb。请帮助

最佳答案

您可以在 Nodepad application by Alex Young 中找到您正在尝试执行的操作的完整示例。 .您应该查看的 2 个重要文件是以下 2 个:

https://github.com/alexyoung/nodepad/blob/master/models.js
https://github.com/alexyoung/nodepad/blob/master/app.js

模型的一部分如下所示:

  User = new Schema({
'email': { type: String, validate: [validatePresenceOf, 'an email is required'], index: { unique: true } },
'hashed_password': String,
'salt': String
});

User.virtual('id')
.get(function() {
return this._id.toHexString();
});

User.virtual('password')
.set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.hashed_password = this.encryptPassword(password);
})
.get(function() { return this._password; });

User.method('authenticate', function(plainText) {
return this.encryptPassword(plainText) === this.hashed_password;
});

User.method('makeSalt', function() {
return Math.round((new Date().valueOf() * Math.random())) + '';
});

User.method('encryptPassword', function(password) {
return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
});

User.pre('save', function(next) {
if (!validatePresenceOf(this.password)) {
next(new Error('Invalid password'));
} else {
next();
}
});

我想他也是explains the code on the dailyjs site .

关于mongodb - 在 node.js 和 mongodb 中创建注册和登录表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8051631/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com