I am completely new to nodejs and am trying to create authorization.
I watched a lot of documentation, but I didn’t understand how to fasten a request to the postgre database to my passport in order to check for an account and confirm the password.

What I have now:

passport.use(new LocalStrategy({ usernameField: 'ogrn', passwordField: 'okpo' }, function(username, password, done) { User.findOne({username : username}, function(err, user) { return err ? done(err) : user ? password === user.password ? done(null, user) : done(null, false, {message: 'Incorrect password.'}) : done(null, false, {message: 'Incorrect username.'}); }); })); 

So who can explain to me how to make a request to the database in this fragment? Or it is somehow screwed before, could not understand.

    1 answer 1

    Let's assume that you are not using ORM to interact with the database.

    The asynchronous function for retrieving a user from a PostgreSQL database can be:

     // fetch_user.js var pg = require('pg'); module.exports = fetchUser = function (username, done) { // Создаем клиента базы данных. По-хорошему, здесь вы должны использовать // пул соединений, заранее сконфигурированный и передваемый // "из вне". Для простоты я использую одиночного клиента БД. var client = new pg.Client(); // Устанавливаем соединение с БД. client.connect(function (err) { if (err) { // Ошибка подключения. Возвращаем ее на уровень выше. return done(err); } // Отправляем запрос в базу. client.query( 'SELECT * FROM users WHERE username = $1::text', [username], function (err, results) { // Закрываем соединение с БД. client.end(); // Возвращаем ошибку или результат запроса. // Если пользователь не найден, возвращаем null вместо данных. done(err, result.rows[0] || null); } ); }); }; 

    And this is how it can be used:

     var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, fetchUser = require('./fetch_user.js'); passport.use(new LocalStrategy({ usernameField: 'ogrn', passwordField: 'okpo' }, function(username, password, done) { fetchUser(username, function(err, user) { if (err) { return done(err); } if (!user) { return done(null, false, {message: 'Incorrect username.'}); } // По-хорошему, в базе вы должны хранить хэш пароля. А раз так, то // переменную "password" стоит захешировать перед сравнением. if (user.password !== password) { return done(null, false, {message: 'Incorrect password.'}); } done(null, user); }); }));