forked from tdjsnelling/sqtracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateAdminUser.js
More file actions
59 lines (52 loc) · 1.5 KB
/
Copy pathcreateAdminUser.js
File metadata and controls
59 lines (52 loc) · 1.5 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
import bcrypt from "bcrypt";
import crypto from "crypto";
import jwt from "jsonwebtoken";
import User from "../schema/user";
import { sendVerificationEmail } from "../controllers/user";
const createAdminUser = async (mail) => {
const existingAdmin = await User.findOne({ username: "admin" }).lean();
if (!existingAdmin) {
const created = Date.now();
const hash = await bcrypt.hash("admin", 10);
const adminUser = new User({
username: "admin",
email: process.env.SQ_ADMIN_EMAIL,
role: "admin",
password: hash,
created,
remainingInvites: Number.MAX_SAFE_INTEGER,
emailVerified: process.env.SQ_DISABLE_EMAIL,
});
adminUser.uid = crypto
.createHash("sha256")
.update(adminUser._id.toString())
.digest("hex")
.slice(0, 10);
adminUser.token = jwt.sign(
{
id: adminUser._id,
created,
role: "admin",
},
process.env.SQ_JWT_SECRET
);
await adminUser.save();
if (!process.env.SQ_DISABLE_EMAIL) {
const emailVerificationValidUntil = created + 48 * 60 * 60 * 1000;
const emailVerificationToken = jwt.sign(
{
user: process.env.SQ_ADMIN_EMAIL,
validUntil: emailVerificationValidUntil,
},
process.env.SQ_JWT_SECRET
);
await sendVerificationEmail(
mail,
process.env.SQ_ADMIN_EMAIL,
emailVerificationToken
);
}
console.log("[sq] created initial admin user");
}
};
export default createAdminUser;