1 | "use strict"
|
2 |
|
3 | const bcrypt = require("bcrypt")
|
4 | const NUM_ROUNDS = 6
|
5 |
|
6 | async function hash(token) {
|
7 | return await bcrypt.hash(token, NUM_ROUNDS)
|
8 | }
|
9 |
|
10 | async function compare(token, encryptedToken, newHashCallback) {
|
11 | try {
|
12 | let res = await bcrypt.compare(token, encryptedToken)
|
13 | let rounds = bcrypt.getRounds(encryptedToken)
|
14 |
|
15 | if (res && newHashCallback && NUM_ROUNDS !== rounds) {
|
16 | process.nextTick(async () => newHashCallback(await hash(token)))
|
17 | }
|
18 |
|
19 | return res
|
20 | } catch (e) {
|
21 | return false
|
22 | }
|
23 | }
|
24 |
|
25 | function addBcryptCheck(model) {
|
26 | model.tokens = {}
|
27 | model.beforeSave(async (self) => {
|
28 | if(self.token) {
|
29 | self.encryptedToken = await hash(self.token)
|
30 | }
|
31 | })
|
32 | model.prototype.isValidToken = async function(token) {
|
33 | if(model.tokens[this.encryptedToken] == token) return true
|
34 | let res = await compare(token, this.encryptedToken, (newEncryptedToken) => {
|
35 | this.encryptedToken = newEncryptedToken
|
36 | this.save()
|
37 | })
|
38 | model.tokens[this.encryptedToken] = (res ? token: null)
|
39 | return res
|
40 | }
|
41 | }
|
42 | module.exports = { hash, compare, addBcryptCheck}
|