index.ts 6.05 KB
Newer Older
1
2
import * as cookies from 'es-cookie';
// utilities
3
import { log } from '@gringlobal/client/utilities/debug';
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

/**
 * A very wordy comparison of two arrays
 */
export function arraysEqual(a: any[], b: any[]): boolean {
  if ((a === null || a === undefined) && (b === null || b === undefined)) {
    return true;
  } else if ((a === null || a === undefined) && (b !== null || b !== undefined)) {
    return false;
  } else if ((a !== null || a !== undefined) && (b === null || b === undefined)) {
    return false;
  } else if (a.length !== b.length) {
    return false;
  } else {
    for (let i = 0; i < a.length && i < b.length; i++) {
      if (a[i] !== b[i]) {
        return false;
      }
    }
    return true;
  }
}

export const withPermissionCheck = (...permissions) => (promised) => (dispatch, getState) => {
  return promised(dispatch, getState).then((res) => {
    if (!Object.entries(res._permissions).reduce((res, [key, val]) => res && (!permissions.includes(key) || val), true)) {
      throw { code: 401, message: 'You have no rights to view this page' };
    }
    return res;
  });
};

export function saveCookies(resp, expireOn: number, apiUrl: string) {
  const domain = apiUrl.includes('.') ? `.${apiUrl.split('.').filter((item, index, arr) => index > arr.length - 3).join('.')}` : 'localhost';

  const expDate = new Date(expireOn);
  log(`Saving cookies to expire on ${expDate}`);
  cookies.set('access_token', resp.access_token, { domain, path: '/', expires: expDate });
  cookies.set('authorities', JSON.stringify(resp.authorities), { domain,  path: '/', expires: expDate });
  if (resp.refresh_token) {
    cookies.set('refresh_token', resp.refresh_token, { domain,  path: '/', expires: expDate });
  } else {
Matija Obreza's avatar
Matija Obreza committed
46
    cookies.remove('refresh_token');
47
48
49
50
51
  }
}

export function clearCookies() {
  log('Clearing cookies');
Matija Obreza's avatar
Matija Obreza committed
52
  ['authorities', 'access_token', 'refresh_token'].forEach((key) => cookies.remove(key));
53
54
55
56
57
58
59
60
61
62
63
}


export function isNumeric(value: any): boolean {
  return !isNaN(value - parseFloat(value));
}

/**
 * This function remaps reference-by-ID to full objects
 *
 * Examples:
64
65
66
67
 *   dereferenceReferences2(paged.content, { uuid: [ 'owner', 'foobar' ], id: [ 'institute' ]});
 *
 * `_self` allows you to handle top-level references:
 *   dereferenceReferences2(paged.content, { _self: 'user', uuid: [ 'user', 'owner', 'foobar' ], id: [ 'institute' ]});
68
69
70
71
 *
 * @param content The list of objects
 * @param referenceMap The map of ID-keys of properties
 */
72
export function dereferenceReferences(content: any[], referenceMap: any, refs: { [key: string]: any } = {}): any[] {
73
74
  // Convert cross-references to Partner object
  if (!content) {
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    return content;
  }

  const { _self, ...refMap } = referenceMap;
  let _selfName = null;
  if (_self) {
    _selfName = Object.keys(refMap).filter((id) => {
      // check if mapping for this id contains _self name
      return refMap[id].filter((elem) => elem === _self).length === 1;
    });
    if (_selfName.length === 1) {
      _selfName = _selfName[0];
      console.log(`_Self ${_self} is by ${_selfName}`);
      if (! refs[`${_self}`]) {
        refs[`${_self}`] = {}; // initialize map
      }
    }
  } else {
    // console.log('No _self found in', referenceMap);
  }

  if (_selfName) {
    // scan for selfs first
    content.forEach((entry) => {
      if (entry && typeof entry === 'object') {
        // add self if declared
        // console.log(`Registered _self reference ${_self}.'${entry[_selfName]}' using ${_selfName}`);
        refs[`${_self}`][entry[`${_selfName}`]] = entry;
      }
    });
105
106
107
108
109
110
111
  }

  // deep search first
  content.forEach((entry) => {
    if (entry && typeof entry === 'object') {
      for (const p of Object.keys(entry)) {
        if (entry[p] && typeof entry[p] === 'object') {
112
          dereferenceReferences([entry[p]], refMap, refs);
113
114
115
116
117
118
        }
      }
    }
  });

  // console.log('Handling references', content);
119
120
  Object.keys(refMap).forEach((id) => {
    const props: string[] = refMap[id];
121
    // iterate over unique prop names
122
    props.filter((elem, pos, arr) => arr.indexOf(elem) === pos).forEach((prop) => {
123
124
125
126
127
      const prop0 = Array.isArray(props) ? props[0] : props; // use 1st element as master prop key
      if (!refs[prop0]) {
        refs[prop0] = {}
      } // setup

128
129
130
131
132
133
134
135
136
137
138
139
140
141
      // console.log(`Dereferencing ${prop}.${id} as ${prop0}`);

      content.filter((entry) => entry && entry[prop] && typeof entry[prop] === 'object' && entry[prop][id])
        .map((entry) => entry[prop])
        .forEach((ref) => {
          refs[prop0][`${ref[id]}`] = ref;
          // console.log(`Registered ${prop0}.'${ref[id]}' using ${id} in`, refs[prop0]);
        });

      content.filter((entry) => entry && entry[prop] && typeof entry[prop] !== 'object')
        .forEach((entry) => {
          // console.log(`Looking up ${prop0}.'${entry[prop]}' in`, refs[prop0]);
          entry[prop] = refs[prop0][`${entry[prop]}`] || entry[prop]; // keep original if not found
        });
142
143
    });
  });
144
145
146
147
148
149
150
151
152
153
154
155

  if (_selfName) {
    content.forEach((entry, index) => {
      if (entry && typeof entry !== 'object') {
        // add self if declared
        // console.log(`Looking up _self reference ${_self}.'${entry}'`);
        content[index] = refs[`${_self}`][`${entry}`];
      }
    });
  }

  return content;
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
}

export function insertAtCaret(element, myValue) {
  const doc = document as any;
  if (doc.selection) {
    // For browsers like Internet Explorer
    element.focus();
    const sel = doc.selection.createRange();
    sel.text = myValue;
    element.focus();
  } else if (element.selectionStart || element.selectionStart === '0') {
    // For browsers like Firefox and Webkit based
    const startPos = element.selectionStart;
    const endPos = element.selectionEnd;
    const scrollTop = element.scrollTop;
    element.value = element.value.substring(0, startPos) + myValue + element.value.substring(endPos, element.value.length);
    element.focus();
    element.selectionStart = startPos + myValue.length;
    element.selectionEnd = startPos + myValue.length;
    element.scrollTop = scrollTop;
  } else {
    element.value += myValue;
    element.focus();
  }
}