2011-11-08 146 views
38

我是node.js的新手,並且想爲user.also創建一個註冊和登錄頁面,並且必須爲用戶進行適當的授權。我想存儲用戶信息裏面mongodb數據庫。我怎麼能做到這一點。有人給我提供代碼這樣做,所以我可以開始使用node.js和mongodb.Please幫助在node.js和mongodb中創建註冊和登錄表單

+0

到目前爲止,您的嘗試有哪些? – beny23

回答

42

你可以找到你在做什麼完整的示例做登錄試圖在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

+0

Alex的教程正是我所需要的。 – mwilcox

+3

http://dailyjs.com/2010/12/06/node-tutorial-5/這是驗證頁面。 –

10

爲了一個簡單的方法開始看看ExpressJS + MongooseJS + MongooseAuth

特別是,最後插件提供了一個標準的簡單的方法使用幾種不同的身份驗證方法(密碼,Facebook,微博等)

+0

有沒有辦法我可以在數據庫(mongodb)中存儲登錄詳細信息,稍後檢索詳細信息並檢查特定用戶是否存在於數據庫中,如果是,那麼用戶將被允許登錄並重定向到另一個頁面。else他不會被任何人提供給我參考代碼 –

+1

@DHHamid Mongoose-auth自動將用戶信息(在註冊,Facebook,Twitter等後從密碼獲取)存儲到MongoDB中。克隆它並運行示例。有關更多信息,請參閱Readme.md。 – k00k

+1

值得注意的是,兩年後,Sadly MongooseAuth沒有得到很好的維護,並且使用PassportJS代替。 – Petrogad

21

我寫了一個boilerplate projectexactly this.它支持賬戶創建,通過電子郵件獲取密碼,會話,當用戶返回時記住用戶的本地cookie以及通過bcyrpt安全密碼加密。

There's also a detailed explanation of the project's architecture on my blog.

+0

演示很不錯..但代碼是以不是很友好的方式編寫的:/ – tUrG0n

+3

我不同意。除非他自2012年6月13日起改變了它。我認爲代碼結構良好,我可以立即告訴發生了什麼。值得檢查。 –

+0

這對我來說是一個很棒的樣板。我絕對修改它(如你應該),以適應我的需求。我在辯論將這種方法與護照結合起來。我也將切換到Mongoose來處理MongoDB,但還沒有到那裏。無論如何,這是一個很好的參考項目。 – BRogers