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;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.