4
\$\begingroup\$

I'm using Passport in Node.js app to authenticate user by email and password (login) and also by token.

Email and password are used only when user is logging in. Passport local strategy generates token when user email and password matched. Token will be later used for bearer token authentication.

It would be nice to hear if code style and structure are good. Is the flow control (Promise.reject with CancellationError) written well?

'use strict';
import {User} from '../models';
import passport from 'passport';
import local from 'passport-local';
import token from 'passport-http-bearer';
import Promise from 'bluebird';
import generateToken from '../helpers/token';
passport.use('local', new local.Strategy({
 usernameField: 'email',
 passwordField: 'password'
 },
 (email, password, done) => {
 User.findOne({where: {email}})
 .then(user =>
 user ?
 user.comparePassword(password)
 : Promise.reject(new Promise.CancellationError('Wrong email or password'))
 )
 .spread((isMatch, user) =>
 isMatch ?
 generateToken()
 .then(token => user.update({token}))
 .then(done(null, user.token))
 : Promise.reject(new Promise.CancellationError('Wrong email or password'))
 )
 .catch(Promise.CancellationError, info => done(null, false, info))
 .catch(err => done(err));
 }));
passport.use('token', new token.Strategy((token, done) => {
 User.findOne({where: {token}})
 .then(user => user ? done(null, user, {scope: 'all'}) : done(null, false))
 .catch(err => done(err));
}));
export var tokenAuthentication = passport.authenticate('token', {session: false});
export default passport;
asked May 4, 2016 at 12:53
\$\endgroup\$

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.