Usando Passport para autenticação/login no Node.js

De Basef
Revisão de 15h10min de 30 de outubro de 2016 por Admin (discussão | contribs)

Ir para: navegação, pesquisa

O código abaixo foi utilizado com a versão 4 do Express e utiliza sessão com Cookies:

1) Instalar dependências do Node.js:

npm install passport --save
npm install passport-local --save
npm install body-parser --save
npm install cookie-parser --save
npm install cookie-session --save
npm install connect-ensure-login --save

2) Configurar o Passport:

A configuração do Passport deve ser feita após o término da inicialização do Express.

// Express initialization
var app = express();
 
...
 
var passport       = require('passport');
var LocalStrategy  = require('passport-local').Strategy;
 
app.use(express.static('public'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('cookie-session')({ secret: 'My app secret' }));
 
app.use(passport.initialize());
app.use(passport.session());
 
passport.use(new LocalStrategy({
        usernameField: 'email', // field name from HTML login page
        passwordField: 'password' // field name from HTML login page
    },
    function(email, password, done) {
        findByEmail(email).then(function(customer) { // You must provide a way to get the customer entity
            if (customer == null) {
                return done(null, false, { message: 'Incorrect email.' });
            }
 
            if (customer.password != password) {
                return done(null, false, { message: 'Incorrect password.' });
            }
 
            return done(null, customer);
        });
    }
));
 
passport.serializeUser(function(customer, done) {
    done(null, customer.email);
});
 
passport.deserializeUser(function(email, done) {
    getCustomerByEmail(email).then(customer) { // You must provide a way to get the customer entity
        done(null, customer);
    }
});
 
app.get('/login', function (req, res) {
    // Render your login page with 'email' and 'password' input fields.
    // Submit it with method=POST and action=login
});
 
// 'local' here means Passport's local authentication (using user/pass). There are other methods like Facebook, Twitter, etc
app.post('/login', passport.authenticate('local', {
        failureRedirect: '/login'
    }),
    function(req, res, next) {
        res.redirect('/'); // after login, will be redirected to home
    }
);
 
app.get('/logout', function(req, res) {
    req.logout();
    res.redirect('/'); // after logout, will be redirected to home
});