Shelf/src/models/user.ts

139 lines
3.5 KiB
TypeScript
Raw Normal View History

2022-05-19 22:38:28 +00:00
import client from '../database';
import bcrypt from 'bcrypt';
const { BCRYPT_PASSWORD, SALT_ROUNDS} = process.env
const pepper = BCRYPT_PASSWORD
const saltRounds = SALT_ROUNDS
export type User = {
id?: number;
2022-05-20 02:55:14 +00:00
firstName?: string;
lastName?: string;
2022-05-19 22:38:28 +00:00
username: string;
password: string;
}
export class UserStore {
async index(): Promise<User> {
try {
const conn = await client.connect()
const sql = 'SELECT * FROM users'
const result = await conn.query(sql)
const user = result.rows[0]
conn.release()
return user
} catch (err) {
throw new Error(`Cannot get any users ${err}`)
}
}
async read(id: number): Promise<User> {
try {
const conn = await client.connect()
const sql = 'SELECT * FROM users WHERE id=($1)'
const result = await conn.query(sql, [id])
const user = result.rows[0]
conn.release()
return user
} catch (err) {
throw new Error(`Could not find user ${id}. Error: ${err}`)
}
}
async create(u: User): Promise<User> {
try {
const conn = await client.connect()
const sql = 'INSERT INTO users (firstName, lastName, username, password) VALUES ($1, $2, 3$, 4$) RETURNING *'
const hash = bcrypt.hashSync(
u.password + pepper,
parseInt(saltRounds as string, 10)
)
const result = await conn.query(sql, [u.firstName, u.lastName, u.username, hash])
const user = result.rows[0]
conn.release()
return user
} catch(err) {
throw new Error(`Could not add a new user ${u.firstName}. Error: ${err}`)
}
}
async update(u: User): Promise<User> {
try {
const conn = await client.connect()
const sql = 'UPDATE users SET fristName=$1, lastName=$2, username=$3, password=$4 WHERE id=$5 RETURNING *'
const result = await conn.query(sql, [u.firstName, u.lastName, u.username, u.password, u.id])
const user = result.rows[0]
conn.release()
return user
} catch (err) {
throw new Error(`Could not update user ${u.firstName}. Error: ${err}`)
}
}
async delete(id: Number): Promise<User> {
try {
const conn = await client.connect()
const sql = 'DELETE FROM users WHERE id=($1)'
const result = await conn.query(sql, [id])
const user = result.rows[0]
conn.release()
return user
} catch (err) {
throw new Error(`Could not delete user ${id}. Error: ${err}`)
}
}
async authenticate(username: string, password: string): Promise<User | null> {
try {
const conn = await client.connect()
const sql = 'SELECT password_digest FROM users WHERE username=($1)'
const result = await conn.query(sql, [username])
console.log("password + pepper :", password + pepper )
if(result.rows.length) {
const user = result.rows[0]
console.log(user)
if (bcrypt.compareSync(password + pepper, user.password_digest)) {
return user
}
}
conn.release()
return null
} catch (err) {
throw new Error(`Could not find user ${username}. Error: ${err}`)
}
}
}