From 655ec610fcce8dd7748f10772d520bdff4f7c78e Mon Sep 17 00:00:00 2001 From: Arne Rief Date: Fri, 19 Dec 2025 20:03:03 +0100 Subject: Basic setup & login --- backend/src/controllers/generateAdmin.ts | 48 ++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 backend/src/controllers/generateAdmin.ts (limited to 'backend/src/controllers/generateAdmin.ts') diff --git a/backend/src/controllers/generateAdmin.ts b/backend/src/controllers/generateAdmin.ts new file mode 100644 index 0000000..045fd2d --- /dev/null +++ b/backend/src/controllers/generateAdmin.ts @@ -0,0 +1,48 @@ +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; -- cgit v1.2.3