aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/modules/passport-local.js
diff options
context:
space:
mode:
Diffstat (limited to 'modules/passport-local.js')
-rw-r--r--modules/passport-local.js85
1 files changed, 85 insertions, 0 deletions
diff --git a/modules/passport-local.js b/modules/passport-local.js
new file mode 100644
index 0000000..939873f
--- /dev/null
+++ b/modules/passport-local.js
@@ -0,0 +1,85 @@
+
+mongoose.connect('localhost', 'test');
+
+var db = mongoose.connection;
+db.on('error', console.error.bind(console, 'connection error:'));
+db.once('open', function callback() {
+ console.log('Connected to MongoDB');
+})
+
+// User schema
+var userSchema = mongoose.Schema({
+ username: { type: String, required: true, unique: true },
+ email: { type: String, required: true, unique: true },
+ password: { type: String, required: true, unique: true},
+});
+
+// Bcrypt middleware
+userSchema.pre('save', function(next) {
+ var user = this;
+
+ if (!user.isModified('password')) return next();
+
+ bcrypt genSalt(SALT_WORK_FACTOR, function(err, salt) {
+ if (err) return next(err);
+
+ bcrypt.hash(user.password, salt, function(err, hash) {
+ if (err) return next(err);
+ user.password = hash;
+ next();
+ });
+ });
+});
+
+// Password verification
+userSchema.methods.comparePassword = function(candidatePassword, callback) {
+ bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
+ if (err) return callback(err);
+ callback(null, isMatch);
+ });
+};
+
+
+
+
+// Passport session setup.
+// To support persistent login sessions, Passport needs to be able to
+// serialize users into and deserialize users out of the session. Typically,
+// this will be as simple as storing the user ID when serializing, and finding
+// the user by ID when deserializing.
+exports.passport.serializeUser(function(user, done) {
+ done(null, user.id);
+});
+
+exports.passport.deserializeUser(function(id, done) {
+ User.findById(id, function (err, user) {
+ done(err, user);
+ });
+});
+
+
+// Use the LocalStrategy within Passport.
+// Strategies in passport require a `verify` function, which accept
+// credentials (in this case, a username and password), and invoke a callback
+// with a user object. In the real world, this would query a database;
+// however, in this example we are using a baked-in set of users.
+exports.passport.use(new LocalStrategy(function(username, password, done) {
+ User.findOne({ username: username }, function(err, user) {
+ if (err) return done(err);
+ if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
+ user.comparePassword(password, function(err, isMatch) {
+ if (err) return done(err);
+ if(isMatch) {
+ return done(null, user);
+ } else {
+ return done(null, false, { message: 'Invalid password' });
+ }
+ });
+ });
+}));
+
+
+
+
+
+