src/common/auth-util.js   A
last analyzed

Complexity

Total Complexity 3
Complexity/F 1

Size

Lines of Code 44
Function Count 3

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
wmc 3
c 1
b 0
f 0
nc 4
mnd 0
bc 1
fnc 3
dl 0
loc 44
ccs 9
cts 9
cp 1
crap 0
rs 10
bpm 0.3333
cpm 1
noi 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A auth-util.js ➔ ??? 0 6 1
1
/**
2
 * Auth util functions
3
 *
4
 * @since 1.0.0
5
 */
6
7 4
const JWT = require('jsonwebtoken');
8 4
const config = require('./../config/server.config.js');
9 4
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 4
exports.generateToken = (account, ttl = config.auth.tokenTTL) => JWT.sign({
22
  username: account.username,
23
  role: account.role,
24
  exp: new Date().getTime() + ttl,
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 4
exports.encryptPassword = (credential) => {
36 5
  const hmac = crypto.createHmac('sha256', process.env.SECRET_KEY || config.auth.secretKey);
37 5
  hmac.update(`${credential.username}:${credential.password}`);
38 5
  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