node.js passport autentification with sqlite

后端 未结 2 1886
暖寄归人
暖寄归人 2021-01-31 11:30

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

相关标签:
2条回答
  • 2021-01-31 12:02

    You probably figured it out by now but for someone else you can use this line. const LocalStrategy = require('passport-local').Strategy

    0 讨论(0)
  • 2021-01-31 12:17

    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' }));
    
    0 讨论(0)
提交回复
热议问题