diff options
Diffstat (limited to 'src/helpers/password-helpers.ts')
-rw-r--r-- | src/helpers/password-helpers.ts | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/helpers/password-helpers.ts b/src/helpers/password-helpers.ts new file mode 100644 index 000000000..89c75c752 --- /dev/null +++ b/src/helpers/password-helpers.ts | |||
@@ -0,0 +1,36 @@ | |||
1 | import crypto from 'crypto'; | ||
2 | |||
3 | export function hash(password: crypto.BinaryLike) { | ||
4 | return crypto.createHash('sha256').update(password).digest('base64'); | ||
5 | } | ||
6 | |||
7 | export function scorePassword(password: string) { | ||
8 | let score = 0; | ||
9 | if (!password) { | ||
10 | return score; | ||
11 | } | ||
12 | |||
13 | // award every unique letter until 5 repetitions | ||
14 | const letters = {}; | ||
15 | for (let i = 0; i < password.length; i += 1) { | ||
16 | letters[password[i]] = (letters[password[i]] || 0) + 1; | ||
17 | score += 5.0 / letters[password[i]]; | ||
18 | } | ||
19 | |||
20 | // bonus points for mixing it up | ||
21 | const variations = { | ||
22 | digits: /\d/.test(password), | ||
23 | lower: /[a-z]/.test(password), | ||
24 | upper: /[A-Z]/.test(password), | ||
25 | nonWords: /\W/.test(password), | ||
26 | }; | ||
27 | |||
28 | let variationCount = 0; | ||
29 | Object.keys(variations).forEach((key) => { | ||
30 | variationCount += (variations[key] === true) ? 1 : 0; | ||
31 | }); | ||
32 | |||
33 | score += (variationCount - 1) * 10; | ||
34 | |||
35 | return parseInt(score.toString(), 10); | ||
36 | } | ||