Saturday 10 June 2017

passport-local error 401: Unauthorized

I'm trying to get passport-local to work in my node.js koa2 project. But I only got as far as a 401 "Unauthorized" error, when I try to register a new user..

Mongoose MongoDB connection seems to work (no error, only a warning):

Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will on
ly allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClie
nt.connect with auth credentials.

index.js

require('console-stamp')(console, '[HH:MM:ss.l]')

const cfg = require('./config/config')
const koa = require('koa')
const mount = require('koa-mount')
const static = require('koa-static')
// const Pug = require('koa-pug') //not in this code
const session = require('koa-session')
const mongoose = require('mongoose')
const passport = require('koa-passport')

const app = module.exports = new koa()

mongoose.connect('mongodb://' + cfg.user + ':' + cfg.pass + '@' + cfg.host + '/' + cfg.database + '?authSource=admin')

require('./config/passport')(passport)

app
  .use(session({}, app))
  .use(passport.initialize())
  .use(passport.session())
  .use(mount('/assets', static('./src/views/' + cfg.view)))
  .use(require('./src/routes').routes())
  .use(require('./src/routes/authentication').routes())
  //.use(require('./src/routes/admin').routes())
  .listen(cfg.app_port, () => {
    console.info(cfg.app_name + ' is running on ' + cfg.app_host + ':' + cfg.app_port)
  })
  .on('error', function (err) {
    console.info(err.stack)
  })

src/routes/authentication.js

const cfg = require('../../config/config')
const locals = require('../../config/locals/' + cfg.locals)
const app = require('../../')
const Router = require('koa-router')
const passport = require('koa-passport')

const router = module.exports = new Router()

router
  .get('/' + locals.signup_adress, async (ctx, next) => {
    await ctx.render('signup', {
      title: cfg.app_name
    })
  })
  .post('/' + locals.signup_adress, async (ctx, next) => {
    return passport.authenticate('local-signup', async (err, user, info, status) => {
      if (user === false) {
        ctx.body = { success: false }
        return ctx.throw(401)
      } else {
        ctx.body = { success: true }
        return ctx.login(user)
      }
    })(ctx, next)
  })

config/passport.js

const localStrategy = require('passport-local').Strategy
const user = require('../src/models/user')

module.exports = function (passport) {
  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('local-signup', new localStrategy({
    usernameField: 'username',
    passwordField: 'password',
    passReqToCallback: true
  },
  function (ctx, username, password, done) {
    process.nextTick(function () {
      user.findOne({'local.username': username}, function (err, user) {
        if (err) return done(err)
        if (user) return done(null, false, ctx.flash('signupMessage', 'That username is already taken.'))
        else {
          const newUser = new user()

          newUser.local.username = username;
          newUser.local.email = email;
          newUser.local.password = newUser.generateHash(password);

          newUser.save(function (err) {
            if (err) throw err
            return done(null, newUser)
          });
        }
    })
    })
  }))

  passport.use('local-login', new localStrategy({
    usernameField: 'username',
    passwordField: 'password',
    passReqToCallback: true
  },
  function (ctx, username, password, done) {
    user.findOne({'local.username': username}, function (err, user) {
      if (err) return done(err)
      if (!user) return done(null, false, ctx.flash('loginMessage', 'No user found.'))
      if (!user.validPassword(password)) return done(null, false, ctx.flash('loginMessage', 'Oops! Wrong password.'))
      return done(null, user)
    })
  }))
}



via Dima Kiltau

No comments:

Post a Comment