node.js passport autentification with sqlite

后端 未结 2 1885
暖寄归人
暖寄归人 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: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' }));
    

提交回复
热议问题