From 219cc784b1cf9b7fe83fa46dbc66099411b4588b Mon Sep 17 00:00:00 2001 From: Sianida26 Date: Mon, 29 Jan 2024 00:18:26 +0700 Subject: [PATCH] Added user seeder --- prisma/seed.ts | 4 ++- prisma/seeds/userSeed.ts | 36 +++++++++++++++++++++++++ src/features/auth/authUtils.ts | 1 + src/features/auth/tools/hashPassword.ts | 12 +++++++++ 4 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 prisma/seeds/userSeed.ts create mode 100644 src/features/auth/tools/hashPassword.ts diff --git a/prisma/seed.ts b/prisma/seed.ts index 80d8683..43841e3 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -1,12 +1,14 @@ import { PrismaClient } from "@prisma/client"; import permissionSeed from "./seeds/permissionSeed"; import roleSeed from "./seeds/roleSeed"; +import userSeed from "./seeds/userSeed"; const prisma = new PrismaClient(); async function main() { await permissionSeed(prisma); - await roleSeed(prisma); + await roleSeed(prisma); + await userSeed(prisma); } main() diff --git a/prisma/seeds/userSeed.ts b/prisma/seeds/userSeed.ts new file mode 100644 index 0000000..b18b605 --- /dev/null +++ b/prisma/seeds/userSeed.ts @@ -0,0 +1,36 @@ +import hashPassword from "../../src/features/auth/tools/hashPassword"; +import { User, PrismaClient, Prisma } from "@prisma/client"; +import { DefaultArgs } from "@prisma/client/runtime/library"; +import { log } from "console"; + +export default async function userSeed(prisma: PrismaClient) { + + log("Seeding users...") + + const userData: Prisma.UserUncheckedCreateInput[] = [ + { + email: "superadmin@example.com", + name: "Super Admin", + roles: { + connect: { + code: "super-admin" + } + }, + passwordHash: await hashPassword("123456") + } + ] as const; + + await Promise.all( + userData.map(async (user) => { + await prisma.user.upsert({ + where: { + email: user.email ?? undefined + }, + update: user, + create: user + }) + }) + ) + + console.log("users is seeded successfully") +} diff --git a/src/features/auth/authUtils.ts b/src/features/auth/authUtils.ts index 15949ef..17535e7 100644 --- a/src/features/auth/authUtils.ts +++ b/src/features/auth/authUtils.ts @@ -9,6 +9,7 @@ import UserClaims from "./types/UserClaims"; /** * Hashes a plain text password using bcrypt. * + * @deprecated * @param password - The plain text password to hash. * @returns The hashed password. */ diff --git a/src/features/auth/tools/hashPassword.ts b/src/features/auth/tools/hashPassword.ts new file mode 100644 index 0000000..2ede04c --- /dev/null +++ b/src/features/auth/tools/hashPassword.ts @@ -0,0 +1,12 @@ +import bcrypt from "bcrypt"; +import authConfig from "../../../config/auth"; + +/** + * Hashes a plain text password using bcrypt. + * + * @param password - The plain text password to hash. + * @returns The hashed password. + */ +export default async function hashPassword(password: string): Promise { + return bcrypt.hash(password, authConfig.saltRounds); +} \ No newline at end of file