-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiClient.js
More file actions
76 lines (65 loc) · 2.38 KB
/
Copy pathapiClient.js
File metadata and controls
76 lines (65 loc) · 2.38 KB
1
2
3
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// REST calls to ksg-nett run here in the main process, not in the window. The
// window asks for them over IPC (preload.js). Chromium's network stack checks
// TLS certificates, and the token never reaches the page.
const { net } = require('electron')
const API_URL = process.env.XAPP_API_URL || 'https://ksg-nett.samfundet.no/api/'
let token = null
async function request(method, path, { query, body } = {}) {
const url = new URL(path, API_URL)
for (const [key, value] of Object.entries(query || {})) {
url.searchParams.set(key, value)
}
const headers = { Accept: 'application/json' }
if (token) headers.Authorization = `JWT ${token}`
if (body !== undefined) headers['Content-Type'] = 'application/json'
try {
const response = await net.fetch(url.toString(), {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
})
const text = await response.text()
let data = null
try {
data = text ? JSON.parse(text) : null
} catch {
data = text
}
// The sliding token lives 24 hours from opening Soci, and the backend
// cannot extend it (refresh_exp is also 1 day). A 401 on a call that sent
// the token means it has expired: forget it, and the page shows the login.
const expired = response.status === 401 && Boolean(headers.Authorization)
if (expired) token = null
return { ok: response.ok, status: response.status, data, expired }
} catch (error) {
// No connection, DNS or TLS error. status 0 means "no response".
console.error(error)
return { ok: false, status: 0, data: null, expired: false }
}
}
async function obtainToken(cardUuid) {
token = null
const response = await request('POST', 'authentication/obtain-token', {
body: { card_uuid: cardUuid },
})
if (response.ok) token = response.data.token
return { ok: response.ok, status: response.status }
}
const getProducts = () => request('GET', 'economy/products')
const getBalance = cardUuid =>
request('GET', 'economy/bank-accounts/balance', {
query: { card_uuid: cardUuid },
})
const charge = payload => request('POST', 'economy/charge', { body: payload })
async function terminateSession() {
const response = await request('DELETE', 'economy/sessions/terminate')
if (response.ok) token = null
return response
}
module.exports = {
obtainToken,
getProducts,
getBalance,
charge,
terminateSession,
}