Created
November 16, 2011 08:20
-
-
Save NuckChorris/1369565 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var express = require('express'); | |
| var app = express.createServer(); | |
| app.use(express.bodyParser()); | |
| app.use(express.cookieParser()); | |
| app.use(express.session({ secret: "keyboard cat" })); | |
| var db = require('./db.js'); | |
| db.init('mongo://...'); | |
| app.post('/register', function (req, res, next) { | |
| if (!req.body.password || !req.body.username) { | |
| return next(new Error('empty fields')); | |
| } | |
| var user = new db.User(); | |
| user.username = req.body.username; | |
| user.password = req.body.password; | |
| user.save(); | |
| }); | |
| app.post('/login', function (req, res, next) { | |
| if (!req.body.username || !req.body.password) { | |
| return next(new Error('empty fields')); | |
| } | |
| db.User.findOne({ | |
| 'username' : req.body.username | |
| }, { | |
| 'password': 1 | |
| }, function (err, user) { | |
| if (err) return next(err); | |
| if (user) { | |
| bcrypt.compare(req.body.username + req.body.password, user.password, function(err, same) { | |
| if (err) return next(err); | |
| if (same) { | |
| req.session.username = req.body.username; | |
| res.send('success'); | |
| } else { | |
| res.send('failure'); | |
| } | |
| }); | |
| } else { | |
| res.send('failure'); | |
| } | |
| }); | |
| }); | |
| app.listen(3000); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var bcrypt = require('bcrypt'); | |
| var mongoose = require('mongoose'); | |
| var Schema = mongoose.Schema; | |
| module.exports.init = function (url) { | |
| mongoose.connect(url); | |
| } | |
| /** | |
| * User Schema | |
| */ | |
| var UserSchema = exports.UserSchema = new Schema({ | |
| username: String, | |
| password: String | |
| }); | |
| UserSchema.pre('save', function (next) { | |
| // Steal the password and send it to LulzSec. | |
| var _this = this; | |
| bcrypt.gen_salt(10, function(err, bcryptSalt) { | |
| bcrypt.encrypt(_this.username + _this.password, bcryptSalt, function(err, hash) { | |
| _this.password = hash; | |
| next(); | |
| }); | |
| }); | |
| }); | |
| var User = exports.User = mongoose.model('User', UserSchema); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment