1.0.0 • Published 7 years ago

jwt-authenticator v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
7 years ago

jwt-authenticator

Simple user authentication based in AuthStrategies.

Instalation

$ npm install --save jwt-authenticator
or
$ yarn add jwt-authenticator

Usage

// auth.js

const { 
  Authenticator, // Authenticator Core
  AuthLocal,     // Stategy for local login
  MemoryStore    // Save tokens in memory
} = require('jwt-authenticator')

const auth = new Authenticator({
  secret: 'keyboard cat', // JWT secret
  store: new MemoryStore(),
})

// Serialize user session
auth.serializeUser((userData) => {
  return Promise.resolve(userData.id)
})

// Deerialize user session
auth.serializeUser((userId) => {
  return User.findById(userId)
})

// Register a AuthStrategy
auth.use('local', 
  new AuthLocal((username, password, done) => {
    User.findOne({ username }).then((user) => {
      if(user.comparePassword(password)){
        done(null, user)
      } else {
        done(null, false, {message: 'Invalid Password'})
      }
    }).catch(error => done(error))
  })
)

module.exports = auth // Export instance

app.js

const express = require('express')
const bodyParser = requrie('body-parser')
const auth = requrie('./auth')
const app = express()

// Required for get form data
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())

// Initialize Authenticator
app.use(auth.initialize())

// Logging
app.post('/login', auth.authenticate('local'), (req, res, next) => {
  // OK, authenticated
  res.json({ user })
})

app.get('/secret', auth.protect(), (req, res, next) => {
  // OK, user authenticated
  res.json({ user })
})

app.use((err, req, res, next) => {
  res.json({
    error: err.message
  })
})

Developed by

Colaborate!