|
|
|
const pg = require('../pg')
|
|
|
|
const joinjs = require('join-js').default;
|
|
|
|
const debug = require('debug')('sos:db:user')
|
|
|
|
const mappings = require('../mappings')
|
|
|
|
|
|
|
|
const bcrypt = require('bcrypt')
|
|
|
|
const session = require('./session')
|
|
|
|
|
|
|
|
const user = module.exports = {}
|
|
|
|
|
|
|
|
user.findById = async (user_uuid) => {
|
|
|
|
const query = {
|
|
|
|
text: 'select * from "user" where user_uuid = $1',
|
|
|
|
values: [
|
|
|
|
user_uuid
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
|
|
|
debug(query);
|
|
|
|
|
|
|
|
const {rows} = await pg.query(query)
|
|
|
|
return joinjs.map(rows, mappings, 'userMap', 'user_')[0];
|
|
|
|
}
|
|
|
|
|
|
|
|
user.findByEmail = async (email) => {
|
|
|
|
const query = {
|
|
|
|
text: 'select * from "user" where user_email = $1',
|
|
|
|
values: [
|
|
|
|
email
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
|
|
|
debug(query);
|
|
|
|
|
|
|
|
const {rows} = await pg.query(query)
|
|
|
|
return joinjs.map(rows, mappings, 'userMap', 'user_')[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
user.register = async (email, password) => {
|
|
|
|
const hash = await bcrypt.hash(password, process.env.PW_SALTROUNDS || 10)
|
|
|
|
|
|
|
|
const query = {
|
|
|
|
text: 'select * from register_user($1, $2)',
|
|
|
|
values: [
|
|
|
|
email,
|
|
|
|
hash
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
|
|
|
debug(query);
|
|
|
|
|
|
|
|
const {rows} = await pg.query(query)
|
|
|
|
return joinjs.map(rows, mappings, 'userMap', 'user_')[0];
|
|
|
|
}
|
|
|
|
|
|
|
|
user.login = async (email, password) => {
|
|
|
|
const user = await user.findByEmail(email)
|
|
|
|
|
|
|
|
if(!user){
|
|
|
|
// Avoid early exit timing difference
|
|
|
|
await bcrypt.hash(password)
|
|
|
|
throw new Error("User not found")
|
|
|
|
}
|
|
|
|
|
|
|
|
const passwordCorrect = await bcrypt.compare(password, user.password_hash)
|
|
|
|
|
|
|
|
if(!passwordCorrect)
|
|
|
|
throw new Error("Password incorrect")
|
|
|
|
|
|
|
|
return user
|
|
|
|
}
|