Completed
Push — master ( 77afd5...a883f6 )
by Cyril
01:05
created

lib/cookieAuthentication.js   A

Complexity

Total Complexity 15
Complexity/F 1.88

Size

Lines of Code 65
Function Count 8

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 0
c 2
b 0
f 0
nc 1
dl 0
loc 65
rs 10
wmc 15
mnd 1
bc 16
fnc 8
bpm 2
cpm 1.875
noi 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A cookieAuthentication.js ➔ ??? 0 12 3
1
const requestify = require('requestify');
2
3
let getBaseUrl = (url) => {
4
  if (!url) {
5
    throw new Error('url not specified - can\'t get base url');
6
  }
7
  let index = url.indexOf('rest/');
8
  if (index === -1) {
9
    throw new Error('Invalid url (can\'t find \'rest/\' string) - can\'t get base url');
10
  }
11
  let baseUrl = url.substr(0, index + 5);
12
13
  return baseUrl;
14
};
15
16
let extractSessionCookie = (cookies, cookieName) => {
17
  if (!cookieName) {
18
    throw new Error('cookie name not specified - can\'t extract session cookie');
19
  }
20
  if (!cookies) {
21
    throw new Error('cookies not specified - can\'t extract session cookie');
22
  }
23
  if (!Array.isArray(cookies)) {
24
    throw new Error('cookies is not an array - can\'t extract session cookie');
25
  }
26
27
  try {
28
    var sessionCookie = cookies.find((cookie) => { // eslint-disable-line no-var
29
      let name = cookie.split('=')[0];
30
      let value = cookie.split('=')[1].split(';')[0];
31
      return ((name === cookieName) && (value != '""'));
32
    }).split(';')[0];
33
  } catch (error) {
34
    throw new Error('cookie name not found in cookies - can\'t extract session cookie');
35
  }
36
37
  return sessionCookie;
38
};
39
40
module.exports = {
41
  login: (userName, password, url) => new Promise((resolve, reject) => {
42
    try {
43
      let loginUrl = getBaseUrl(url) + 'auth/1/session';
44
      let body = {'username': userName, 'password': password};
45
      let options = {
46
        cache: {
47
          cache: false,
48
        },
49
      };
50
51
      requestify.post(loginUrl, body, options)
52
        .then((response) => {
53
          resolve(extractSessionCookie(response.headers['set-cookie'], JSON.parse(response.body).session.name));
54
        })
55
        .catch((error) => {
56
          reject(new Error('Can\'t get cookie [' + error.message + ']'));
57
        });
58
    } catch (error) {
59
      reject(new Error('Can\'t get cookie [' + error.message + ']'));
60
    }
61
  }),
62
  getHeader: (sessionCookie) => {
63
    return {'cookie': sessionCookie, 'Cache-Control': 'public, max-age=60'};
64
  },
65
};
66