1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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;
|