This repository has been archived on 2024-04-05. You can view files and clone it, but cannot push or open issues or pull requests.
score-tracker/database/accounts/accounts.js
2021-11-24 20:58:49 -07:00

58 lines
No EOL
1.6 KiB
JavaScript

const database = require('./../database');
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
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) {
const salt = bcrypt.genSaltSync();
const hash = bcrypt.hashSync(password, salt);
const query = `INSERT INTO accounts.users(email, password)
VALUES($1, $2)`;
await database.executeQuery(query, [email, hash]);
}
exports.createUser = createUser;
exports.passport = passport;