rts-app/node/src/lib/db/UserService.js

69 lines
1.9 KiB
JavaScript

import bcrypt from 'bcryptjs'
import { Query } from '@/lib/db/db'
export async function addUser(fname, lname, username, email, password) {
username = username.toLowerCase().trim()
email = email.toLowerCase().trim()
const existingUser = await getUserByUsername(username)
if (existingUser) {
throw new Error('USERNAME_EXISTS')
}
const existingEmail = await getUserByEmail(email)
if (existingEmail) {
throw new Error('EMAIL_EXISTS')
}
const status = 1; // active
const role = 4;
const hash = await bcrypt.hash(password, 10)
const result = await Query(
`INSERT INTO users (first_name, last_name, username, email, password_hash, role_id, status_id)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, first_name, last_name, username, email, password_hash, role_id, status_id`,
[fname, lname, username, email, hash, role, status]
)
return result.rows[0] || null
}
export async function getUserByUsername(username) {
username = username.toLowerCase().trim()
const result = await Query(
`SELECT id, first_name, last_name, username, email, password_hash, role_id, status_id
FROM users
WHERE username = $1`,
[username]
)
return result.rows[0] || null
}
export async function getUserByEmail(email) {
email = email.toLowerCase().trim()
const result = await Query(
`SELECT id, first_name, last_name, username, email, password_hash, role_id, status_id
FROM users
WHERE email = $1`,
[email]
)
return result.rows[0] || null
}
export async function loginUser(usernameOrEmail, password) {
const user = await getUserByUsername(usernameOrEmail) || await getUserByEmail(usernameOrEmail)
if (!user) {
throw new Error('USER_NOT_FOUND')
}
const isMatch = await bcrypt.compare(password, user.password_hash)
if (!isMatch) {
throw new Error('INVALID_CREDENTIALS')
}
return user
}