const database = require('./../database'); const passport = require('passport'); const localStrategy = require('passport-local').Strategy; const bcrypt = require('bcrypt'); class User { constructor(id, email, isAdmin) { this.id = id; this.email = email; this.isAdmin = isAdmin; } } passport.use(new localStrategy({ usernameField: 'email', passwordField: 'password'}, (username, password, cb) => { query = `SELECT user_id, email, password, admin FROM accounts.users WHERE email = $1`; database.executeQuery(query, [username]) .then(result => { if(result.length > 0) { const first = result[0]; const matches = bcrypt.compareSync(password, first[2]); if(matches) { return cb(null, { id: first[0], email: first[1], admin: first[3] }) } else { return cb(null, false) } } else { return cb(null, false) } }); })); passport.serializeUser((user, done) => { done(null, user.id) }) passport.deserializeUser((id, cb) => { query = `SELECT user_id, email, admin FROM accounts.users WHERE user_id = $1`; database.executeQuery(query, [parseInt(id, 10)]) .then(result => { cb(null, result[0]); }); }); async function createUser(email, password, isAdmin) { const salt = bcrypt.genSaltSync(); const hash = bcrypt.hashSync(password, salt); const query = `INSERT INTO accounts.users(email, password, admin) VALUES($1, $2, $3)`; await database.executeQuery(query, [email, hash, isAdmin]); } async function retrieveAll() { const query = `SELECT user_id, email, admin FROM accounts.users ORDER BY email;` const table = await database.executeQuery(query); const accountsList = []; table.forEach((row) => { accountsList.push(new User(row[0], row[1], row[2])); }); return accountsList; } async function getFromID(id) { const query = `SELECT user_id, email, admin FROM accounts.users WHERE user_id = $1;`; const row = (await database.executeQuery(query, [id]))[0]; return new User(id, row[1], row[2]); } exports.createUser = createUser; exports.retrieveAll = retrieveAll; exports.getFromID = getFromID; exports.passport = passport;