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

80 lines
2.2 KiB
JavaScript
Raw Normal View History

2021-11-25 00:56:04 +00:00
const database = require('./../database');
const passport = require('passport');
2021-11-25 03:58:49 +00:00
const localStrategy = require('passport-local').Strategy;
2021-11-25 01:13:33 +00:00
const bcrypt = require('bcrypt');
2021-11-25 00:56:04 +00:00
class User {
constructor(id, email, isAdmin) {
this.id = id;
this.email = email;
this.isAdmin = isAdmin;
}
}
2021-11-25 03:58:49 +00:00
passport.use(new localStrategy({
usernameField: 'email',
passwordField: 'password'},
(username, 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 03:58:49 +00:00
database.executeQuery(query, [username])
2021-11-25 01:13:33 +00:00
.then(result => {
if(result.length > 0) {
const first = result[0];
const matches = bcrypt.compareSync(password, first[2]);
if(matches) {
2021-11-25 03:58:49 +00:00
return cb(null, { id: first[0], email: first[1], admin: first[3] })
2021-11-25 01:13:33 +00:00
}
else
{
2021-11-25 03:58:49 +00:00
return cb(null, false)
2021-11-25 01:13:33 +00:00
}
} else {
2021-11-25 03:58:49 +00:00
return cb(null, false)
2021-11-25 00:56:04 +00:00
}
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
2021-11-25 03:58:49 +00:00
WHERE user_id = $1`;
2021-11-25 01:13:33 +00:00
database.executeQuery(query, [parseInt(id, 10)])
.then(result => {
cb(null, result[0]);
});
});
2021-11-25 04:40:33 +00:00
async function createUser(email, password, isAdmin) {
2021-11-25 01:13:33 +00:00
const salt = bcrypt.genSaltSync();
const hash = bcrypt.hashSync(password, salt);
2021-11-25 04:40:33 +00:00
const query = `INSERT INTO accounts.users(email, password, admin)
VALUES($1, $2, $3)`;
await database.executeQuery(query, [email, hash, isAdmin]);
2021-11-25 01:25:27 +00:00
}
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;
}
2021-11-25 03:58:49 +00:00
exports.createUser = createUser;
exports.retrieveAll = retrieveAll;
2021-11-25 03:58:49 +00:00
exports.passport = passport;