summaryrefslogtreecommitdiff
path: root/backend/src/controllers/generateAdmin.ts
diff options
context:
space:
mode:
authorArne Rief <riearn@proton.me>2025-12-19 20:03:03 +0100
committerArne Rief <riearn@proton.me>2025-12-19 20:03:03 +0100
commit655ec610fcce8dd7748f10772d520bdff4f7c78e (patch)
tree35b79f30d2cb5aea88cf76ce27f480da93cefd32 /backend/src/controllers/generateAdmin.ts
Basic setup & login
Diffstat (limited to 'backend/src/controllers/generateAdmin.ts')
-rw-r--r--backend/src/controllers/generateAdmin.ts48
1 files changed, 48 insertions, 0 deletions
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<AdminCreationResult> = 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;