Passed
Push — master ( a8bdc8...2feb85 )
by
unknown
01:06
created

src/router/common-api-router.js   A

Complexity

Total Complexity 12
Complexity/F 2.4

Size

Lines of Code 48
Function Count 5

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 81.82%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
wmc 12
c 1
b 0
f 0
nc 12
mnd 1
bc 5
fnc 5
dl 0
loc 48
ccs 18
cts 22
cp 0.8182
crap 0
rs 10
bpm 1
cpm 2.4
noi 0

1 Function

Rating   Name   Duplication   Size   Complexity  
B common-api-router.js ➔ ??? 0 17 5
1
/**
2
 * Common Service API router
3
 *
4
 * @since 1.0.0
5
 */
6
7 4
const Joi = require('joi');
8 4
const User = require('./../repository/User');
9 4
const config = require('../config/server.config').url;
10 4
const util = require('../common/common-util');
11 4
const authUtil = require('../common/auth-util');
12 4
const NotifierError = require('../common/Error');
13 4
const logger = require('winston');
14
15 4
module.exports = [
16
  {
17
    method: 'POST',
18
    path: `${config.apiPrefix}/login`,
19
    handler: (request, reply) => {
20 2
      const clientIP = util.getClientIp(request);
21 2
      if (process.env.ALLOWED_IP && !process.env.ALLOWED_IP.includes(clientIP)) {
22
        logger.warn(`[Auth] This client IP is not allowed.: ${clientIP}`);
23
        return reply(new NotifierError(NotifierError.Types.FORBIDDEN_IP_ADDRESS, { remoteAddress: clientIP }));
24
      }
25 2
      if (!request.payload.username || !request.payload.password) {
26
        return reply(new NotifierError(NotifierError.Types.AUTH_MISSING_PARAMS));
27
      }
28 2
      return User.find({ username: request.payload.username }).then((account) => {
29 2
        if (!account || account.length === 0 || !authUtil.comparePassword(request.payload, account[0].password)) {
30 1
          return reply(new NotifierError(NotifierError.Types.AUTH_INVALID_PARAMS));
31
        }
32 1
        const token = authUtil.generateToken(Object.assign({}, account[0], { ip: clientIP }));
33 1
        return reply().state('token', token);
34
      });
35
    },
36
    config: {
37
      auth: false,
38
    },
39
  },
40
  {
41
    method: 'PUT',
42
    path: `${config.apiPrefix}/passwords`,
43 1
    handler: (request, reply) => User.updatePassword(request.auth.credentials.username, request.payload.password)
44 1
      .then(result => reply(result))
45
      .catch(err => reply(err)),
46
    config: {
47
      validate: {
48
        payload: {
49
          password: Joi.string().min(8).required(),
50
        },
51
      },
52
    },
53
  },
54
];
55