/
hash.ts
67 lines (60 loc) · 1.58 KB
/
hash.ts
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
import * as bcrypt from "bcrypt";
import { Satellite } from "../satellite";
/**
* This class is a wrapper for bcrypt library.
*
* This allow users hash data and compare plain data with a hash
* in order to validate it.
*/
export default class HashManager extends Satellite {
public _name = "Hash";
public loadPriority = 400;
/**
* Generate a new bcrypt salt.
*
* @param rounds Number of rounds.
*/
public generateSalt(
rounds: number = this.api.configs.general.saltRounds,
): Promise<string> {
return bcrypt.genSalt(rounds);
}
/**
* Hash data.
*
* @param data Data to hash.
* @param config Additional configuration where you can override
* pre-defined config.
*/
public hash(data: any, config: any = {}): Promise<string> {
config = this.getConfigs(config);
return bcrypt.hash(data, config.salt || config.saltLength);
}
/**
* Compare hash with plain data.
*
* @param plainData Plain data.
* @param hash Hash to compare with.
*/
public compare(plainData, hash): Promise<boolean> {
return bcrypt.compare(plainData, hash);
}
/**
* Get configs to be used on the generation.
*
* @param configs User defined configurations.
*/
private getConfigs(configs: object = {}): object {
return this.api.utils.hashMerge(
{
salt: this.api.configs.general.salt,
saltRounds: this.api.configs.general.saltRounds,
saltLength: this.api.configs.general.saltLength,
},
configs,
);
}
public async load(): Promise<void> {
this.api.hash = new HashManager(this.api);
}
}