-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-and-promote-admin.ts
More file actions
83 lines (70 loc) · 2.16 KB
/
Copy pathcreate-and-promote-admin.ts
File metadata and controls
83 lines (70 loc) · 2.16 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import "dotenv/config";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../src/lib/prisma";
const [, , email, name] = process.argv;
if (!email) {
// eslint-disable-next-line no-console
console.error(
"Usage: tsx scripts/create-and-promote-admin.ts <email> [name]"
);
process.exit(1);
}
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
// eslint-disable-next-line no-console
console.error("DATABASE_URL environment variable is not set");
process.exit(1);
}
const adapter = new PrismaPg({ connectionString });
const prisma = new PrismaClient({ adapter });
async function main(): Promise<void> {
const resolvedName = name || email;
const user = await prisma.user.findUnique({
where: { email: { mode: "insensitive", equals: email } },
include: { profile: true },
});
if (user) {
if (user.profile?.role === "ADMIN") {
// eslint-disable-next-line no-console
console.log(`${email} is already an ADMIN.`);
process.exit(0);
}
if (!user.profile) {
// eslint-disable-next-line no-console
console.error(`User ${email} has no profile. Creating one...`);
await prisma.userProfile.create({
data: { userId: user.id, role: "ADMIN" },
});
// eslint-disable-next-line no-console
console.log(`Created profile and promoted ${email} to ADMIN.`);
process.exit(0);
}
await prisma.userProfile.update({
where: { userId: user.id },
data: { role: "ADMIN" },
});
// eslint-disable-next-line no-console
console.log(`Promoted ${email} to ADMIN.`);
process.exit(0);
}
const userId = crypto.randomUUID();
await prisma.$transaction([
prisma.user.create({
data: { id: userId, email, name: resolvedName, emailVerified: true },
}),
prisma.userProfile.create({
data: { userId, role: "ADMIN" },
}),
]);
// eslint-disable-next-line no-console
console.log(
`Created user ${email} ("${resolvedName}") and promoted to ADMIN.`
);
}
main()
.catch(err => {
// eslint-disable-next-line no-console
console.error(err);
process.exit(1);
})
.finally(() => prisma.$disconnect());