Total Complexity | 3 |
Complexity/F | 1 |
Lines of Code | 44 |
Function Count | 3 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | /** |
||
7 | const JWT = require('jsonwebtoken'); |
||
8 | const config = require('./../config/server.config.js'); |
||
9 | const crypto = require('crypto'); |
||
10 | |||
11 | /** |
||
12 | * Generate auth token |
||
13 | * @param {Object} account |
||
14 | * - {string} username - username for login |
||
15 | * - {string} role - user's role |
||
16 | * - {number} exp - timestamp indicates expiration date |
||
17 | * - {string} ip - client ip address |
||
18 | * @param {number} ttl - time to live in millisecond |
||
19 | * @returns {*} |
||
20 | */ |
||
21 | exports.generateToken = (account, ttl) => JWT.sign({ |
||
22 | username: account.username, |
||
23 | role: account.role, |
||
24 | exp: new Date().getTime() + (ttl || config.auth.tokenTTL), |
||
25 | ip: account.ip, |
||
26 | }, process.env.SECRET_KEY || config.auth.secretKey); |
||
27 | |||
28 | /** |
||
29 | * Encrypt user password |
||
30 | * @param {Object} credential - user inputs |
||
31 | * - {string} username |
||
32 | * - {string} password |
||
33 | * @returns {string} |
||
34 | */ |
||
35 | exports.encryptPassword = (credential) => { |
||
36 | const hmac = crypto.createHmac('sha256', process.env.SECRET_KEY || config.auth.secretKey); |
||
37 | hmac.update(`${credential.username}:${credential.password}`); |
||
38 | return hmac.digest('hex'); |
||
39 | }; |
||
40 | |||
41 | /** |
||
42 | * Compare password from database with password user input |
||
43 | * The password on database is always generated from '[username]:[password]' string. That improves password's security. |
||
44 | * @param {Object} credential - user inputs |
||
45 | * - {string} username |
||
46 | * - {string} password |
||
47 | * @param {string} dbPassword - digested password string from database |
||
48 | * @returns {boolean} |
||
49 | */ |
||
50 | exports.comparePassword = (credential, dbPassword) => exports.encryptPassword(credential) === dbPassword; |
||
51 |