This repository has been archived on 2024-04-05. You can view files and clone it, but cannot push or open issues/pull-requests.
score-tracker/database/accounts/accounts.js

51 lines
1.5 KiB
JavaScript
Raw Normal View History

2021-11-25 00:56:04 +00:00
const database = require('./../database');
const passport = require('passport');
const passportLocal = require('passport-local');
2021-11-25 01:13:33 +00:00
const bcrypt = require('bcrypt');
2021-11-25 00:56:04 +00:00
passport.use(new passportLocal.Strategy((email, password, cb) => {
2021-11-25 01:13:33 +00:00
query = `SELECT user_id, email, password, admin
2021-11-25 00:56:04 +00:00
FROM accounts.users
WHERE email = $1`;
2021-11-25 01:13:33 +00:00
database.executeQuery(query, [email])
.then(result => {
if(result.length > 0) {
const first = result[0];
const matches = bcrypt.compareSync(password, first[2]);
if(matches) {
cb(null, { id: first[0], email: first[1], admin: first[3] })
}
else
{
cb(null, false)
}
} else {
2021-11-25 00:56:04 +00:00
cb(null, false)
}
2021-11-25 01:13:33 +00:00
});
2021-11-25 00:56:04 +00:00
}));
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser((id, cb) => {
2021-11-25 01:13:33 +00:00
query = `SELECT user_id, email, admin
2021-11-25 00:56:04 +00:00
FROM accounts.users
WHERE id = $1`;
2021-11-25 01:13:33 +00:00
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]);
}