import bcrypt from "bcrypt"; import { Request, Response } from "express"; import { QueryResult } from "pg"; import db from "../database/postgres.js"; import type { AdminCreationResult } from "../types/user.js"; import { isPostgresError, PostgresErrorCodes } from "../utils/dbErrorCheck.js"; /* One-time function to generate an admin user with specific email & password in the DB Reason: hash the password with bcrypt for future authentication */ async function generateAdmin(_req: Request, res: Response) { const adminMail = "admin@test.com"; const adminPass = "test123"; try { const hashedPassword = await bcrypt.hash(adminPass, 10); const adminCreation: QueryResult = await db.query( "INSERT INTO users (email, password_hash) VALUES ($1, $2) RETURNING id, email, created_at;", [adminMail, hashedPassword] ); return res.status(201).json({ message: "The admin was created successfully.", admin: adminCreation.rows[0], }); } catch (error) { if ( isPostgresError(error) && error.code === PostgresErrorCodes.UNIQUE_VIOLATION ) { console.error("Error creating the admin: ", error); return res.status(409).json({ message: "Admin already exists.", error: error.message, }); } console.error("Error creating admin: ", error); return res.status(500).json({ message: "Internal server error for admin creation.", error, }); } } export default generateAdmin;