UNPKG

1.1 kBJavaScriptView Raw
1"use strict"
2
3const bcrypt = require("bcrypt")
4const NUM_ROUNDS = 6
5
6async function hash(token) {
7 return await bcrypt.hash(token, NUM_ROUNDS)
8}
9
10async 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
25function 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}
42module.exports = { hash, compare, addBcryptCheck}