Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js passport autentification with sqlite

Its possible use node.js + passport and sqlite database with session? All example only with mongoDb. I want collect all data in sqlite.

like image 710
user3093010 Avatar asked May 05 '14 21:05

user3093010


1 Answers

Below is an example of using passport-local to create a SQLite backed login strategy. Express specific initialization has been omitted.

This example assumes you have a database with the following users table:

CREATE TABLE "users" (
    "id" INTEGER PRIMARY KEY AUTOINCREMENT,
    "username" TEXT,
    "password" TEXT, -- sha256 hash of the plain-text password
    "salt" TEXT -- salt that is appended to the password before it is hashed
)
var crypto = require('crypto');
var sqlite3 = require('sqlite3');

var db = new sqlite3.Database('./database.sqlite3');

// ...

function hashPassword(password, salt) {
  var hash = crypto.createHash('sha256');
  hash.update(password);
  hash.update(salt);
  return hash.digest('hex');
}

passport.use(new LocalStrategy(function(username, password, done) {
  db.get('SELECT salt FROM users WHERE username = ?', username, function(err, row) {
    if (!row) return done(null, false);
    var hash = hashPassword(password, row.salt);
    db.get('SELECT username, id FROM users WHERE username = ? AND password = ?', username, hash, function(err, row) {
      if (!row) return done(null, false);
      return done(null, row);
    });
  });
}));

passport.serializeUser(function(user, done) {
  return done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  db.get('SELECT id, username FROM users WHERE id = ?', id, function(err, row) {
    if (!row) return done(null, false);
    return done(null, row);
  });
});

// ...

app.post('/login', passport.authenticate('local', { successRedirect: '/good-login',
                                                    failureRedirect: '/bad-login' }));
like image 128
Tim Cooper Avatar answered Nov 09 '22 09:11

Tim Cooper