Objection.js: Using with Passport

Created on 26 Sep 2016  路  2Comments  路  Source: Vincit/objection.js

So i just started new project using Koa2 and Passport and found that objection.js is great for Postgres. But i am not sure how it works with Passport? As with moongose you simply create schema and say that usernameField=username. For Objections is it enough if i create properties and just put same usernameField=username? Or my model should be structured different?

Most helpful comment

here is an example if it helps... my User model is called Admin..

import {Model} from 'objection'
import bcrypt from 'bcryptjs'

export default class Admin extends Model {
  static tableName = 'Admin';

  static jsonSchema = {
    type: 'object',
    required: ['username'],

    properties: {
      id: {type: 'integer'},
      name: {type: 'string'},
      username: {type: 'string', default: ''},
      hash: {type: 'string'},
      isSuper: {type: 'boolean', default: false},
      permissions: {type: 'array'},
      created_at: {},
      updated_at: {}
    }
  };

  set password (password) {
    this.hash = bcrypt.hashSync(password, bcrypt.genSaltSync(10))
  };

  verifyPassword (password, callback) {
    bcrypt.compare(password, this.hash, callback)
  };

}

this is the strategy initialization

import passport from 'koa-passport'
import {Strategy as LocalStrategy} from 'passport-local'
import Admin from './models/admin'

passport.use(
  new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password'
  },
  function (username, password, done) {
    Admin
      .query()
      .where('username', username)
      .first()
      .then(function (admin) {
        if (!admin) return done(null, false, { message: 'Unknown user' })

        admin.verifyPassword(password, function (err, passwordCorrect) {
          if (err) { return done(err) }
          if (!passwordCorrect) { return done(null, false) }
          return done(null, admin)
        })
      }).catch(function (err) {
        done(err)
      })
  }
))

passport.serializeUser(function (admin, done) {
  done(null, admin.id)
})

passport.deserializeUser(function (id, done) {
  Admin.query().findById(id).then(function (admin) {
    done(null, admin)
  })
})

and the routes

import Router from 'koa-router'
import passport from 'koa-passport'

const router = Router()

router.get('/login', (ctx, next) => {
  ctx.render('login')
})

router.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }))

router.get('/logout', (ctx, next) => {
  ctx.logout()
  ctx.redirect('/login')
})

export default router

All 2 comments

here is an example if it helps... my User model is called Admin..

import {Model} from 'objection'
import bcrypt from 'bcryptjs'

export default class Admin extends Model {
  static tableName = 'Admin';

  static jsonSchema = {
    type: 'object',
    required: ['username'],

    properties: {
      id: {type: 'integer'},
      name: {type: 'string'},
      username: {type: 'string', default: ''},
      hash: {type: 'string'},
      isSuper: {type: 'boolean', default: false},
      permissions: {type: 'array'},
      created_at: {},
      updated_at: {}
    }
  };

  set password (password) {
    this.hash = bcrypt.hashSync(password, bcrypt.genSaltSync(10))
  };

  verifyPassword (password, callback) {
    bcrypt.compare(password, this.hash, callback)
  };

}

this is the strategy initialization

import passport from 'koa-passport'
import {Strategy as LocalStrategy} from 'passport-local'
import Admin from './models/admin'

passport.use(
  new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password'
  },
  function (username, password, done) {
    Admin
      .query()
      .where('username', username)
      .first()
      .then(function (admin) {
        if (!admin) return done(null, false, { message: 'Unknown user' })

        admin.verifyPassword(password, function (err, passwordCorrect) {
          if (err) { return done(err) }
          if (!passwordCorrect) { return done(null, false) }
          return done(null, admin)
        })
      }).catch(function (err) {
        done(err)
      })
  }
))

passport.serializeUser(function (admin, done) {
  done(null, admin.id)
})

passport.deserializeUser(function (id, done) {
  Admin.query().findById(id).then(function (admin) {
    done(null, admin)
  })
})

and the routes

import Router from 'koa-router'
import passport from 'koa-passport'

const router = Router()

router.get('/login', (ctx, next) => {
  ctx.render('login')
})

router.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }))

router.get('/logout', (ctx, next) => {
  ctx.logout()
  ctx.redirect('/login')
})

export default router

@arcanewater Did you solve your problem? Please close this if so.

Was this page helpful?
0 / 5 - 0 ratings