Passed
Push — master ( c6b313...ea8146 )
by Kyungmi
01:36
created

auth-util.js ➔ ???   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
c 3
b 0
f 0
nc 1
dl 0
loc 6
rs 9.4285
nop 2
1
/**
2
 * Auth util functions
3
 *
4
 * @since 1.0.0
5
 */
6
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