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

Dar*_*mid 38 mongodb node.js express

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

ale*_*lex 42

您可以在Alex YoungNodepad应用程序中找到您想要做的完整示例.您应该看看的两个重要文件是这两个:

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();
    }
  });
Run Code Online (Sandbox Code Playgroud)

我想他也解释了dailyjs网站上的代码.

  • http://dailyjs.com/2010/12/06/node-tutorial-5/这是验证页面. (3认同)

bra*_*sch 21

我写了一个样板项目来完成这个.它支持帐户创建,通过电子邮件进行密码检索,会话,本地cookie,用于在用户返回时记住用户,并通过bcyrpt保护密码加密.

我的博客上还详细解释了该项目的架构.

  • 我不同意.除非他自2012年6月13日以来更改了它.我认为代码结构合理,我可以立即告诉发生了什么.值得一试. (3认同)

Gat*_* VP 10

有关入门的简便方法,请查看ExpressJS + MongooseJS + MongooseAuth.

特别是,最后一个插件提供了使用几种不同身份验证方法(密码,Facebook,Twitter等)进行登录的标准简单方法.