Created
August 28, 2015 21:20
-
-
Save jonmadison/70b5879ecf04f683fd0f to your computer and use it in GitHub Desktop.
0 to API - config/passport.js
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 mongoose = require('mongoose') | |
| , LocalStrategy = require('passport-local').Strategy | |
| , BearerStrategy = require('passport-http-bearer').Strategy | |
| , User = mongoose.model('User') | |
| , util = require('../util'); | |
| module.exports = function (passport, config, logger) { | |
| passport.serializeUser(function(user, done) { | |
| done(null, user.id); | |
| }); | |
| passport.deserializeUser(function(id, done) { | |
| User.findById(id, function(err, user) { | |
| done(err, user); | |
| }); | |
| }); | |
| passport.use(new LocalStrategy({ | |
| usernameField: 'email', | |
| passwordField: 'password' | |
| }, | |
| function(email, password, done) { | |
| logger.debug("LocalStrategy tapped, calling User.isValidUserPassword"); | |
| User.isValidUserPassword(email, password, function(err,doc){ | |
| if(err) { | |
| logger.debug("User.isValidUserPassword failed: " + JSON.stringify(err)); | |
| return done(err.error); | |
| } | |
| //save a token for the user | |
| if(doc) { | |
| doc.token = util.newToken(); | |
| doc.save(function(err,doc) { | |
| if(err) done(err); | |
| return done(null,doc); | |
| }); | |
| } | |
| }); | |
| })); | |
| passport.use(new BearerStrategy( | |
| function(token, done) { | |
| // logger.debug("BearerStrategy looking for token: " + token); | |
| User.findOne({ token: token }, function (err, user) { | |
| if (err) { return done(err); } | |
| if (!user) { | |
| // logger.debug('BearerStrategy: user not found'); | |
| return done(null, false); | |
| } | |
| // logger.debug('BearerStrategy: user found:' + JSON.stringify(user)); | |
| return done(null, user, { scope: 'all' }); | |
| }); | |
| } | |
| )); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment