forked from umami-software/umami
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchange-password.js
98 lines (85 loc) · 2.1 KB
/
change-password.js
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
require('dotenv').config();
const bcrypt = require('bcryptjs');
const chalk = require('chalk');
const prompts = require('prompts');
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const SALT_ROUNDS = 10;
const runQuery = async query => {
return query.catch(e => {
throw e;
});
};
const updateAccountByUsername = (username, data) => {
return runQuery(
prisma.account.update({
where: {
username,
},
data,
}),
);
};
const hashPassword = password => {
return bcrypt.hashSync(password, SALT_ROUNDS);
};
const changePassword = async (username, newPassword) => {
const password = hashPassword(newPassword);
return updateAccountByUsername(username, { password });
};
const getUsernameAndPassword = async () => {
let [username, password] = process.argv.slice(2);
if (username && password) {
return { username, password };
}
const questions = [];
if (!username) {
questions.push({
type: 'text',
name: 'username',
message: 'Enter account to change password',
});
}
if (!password) {
questions.push(
{
type: 'password',
name: 'password',
message: 'Enter new password',
},
{
type: 'password',
name: 'confirmation',
message: 'Confirm new password',
},
);
}
const answers = await prompts(questions);
if (answers.password !== answers.confirmation) {
throw new Error(`Passwords don't match`);
}
return {
username: username || answers.username,
password: answers.password,
};
};
(async () => {
let username, password;
try {
({ username, password } = await getUsernameAndPassword());
} catch (error) {
console.log(chalk.redBright(error.message));
return;
}
try {
await changePassword(username, password);
console.log('Password changed for user', chalk.greenBright(username));
} catch (error) {
if (error.message.includes('RecordNotFound')) {
console.log('Account not found:', chalk.redBright(username));
} else {
throw error;
}
}
prisma.$disconnect();
})();