1 | const fs = require('fs');
|
2 |
|
3 | const axios = require('axios');
|
4 | const querystring = require('querystring');
|
5 |
|
6 | const { Log } = require('./logger');
|
7 |
|
8 | class SquidexTokenManager {
|
9 | constructor(url, id, secret, debugTokenFile) {
|
10 | this.connectUrl = url;
|
11 | this.client_id = id;
|
12 | this.client_secret = secret;
|
13 | this.debugTokenFile = debugTokenFile;
|
14 |
|
15 |
|
16 | if (debugTokenFile && fs.existsSync(debugTokenFile)) {
|
17 | this.accessToken = JSON.parse(fs.readFileSync(debugTokenFile));
|
18 | }
|
19 | }
|
20 |
|
21 | |
22 |
|
23 |
|
24 | isTokenValid() {
|
25 | return this.secondsSinceCreation() < this.accessToken.expires_in;
|
26 | }
|
27 |
|
28 | |
29 |
|
30 |
|
31 | async getToken() {
|
32 |
|
33 | if (!this.accessToken) {
|
34 | await this.refresh();
|
35 | } else if (!this.isTokenValid()) {
|
36 |
|
37 | await this.refresh();
|
38 | }
|
39 | return this.accessToken.access_token;
|
40 | }
|
41 |
|
42 | |
43 |
|
44 |
|
45 | async refresh() {
|
46 | const accessToken = await axios.post(this.connectUrl,
|
47 | querystring.stringify({
|
48 | grant_type: 'client_credentials',
|
49 | client_id: this.client_id,
|
50 | client_secret: this.client_secret,
|
51 | scope: 'squidex-api',
|
52 | }), {
|
53 | headers: {
|
54 | 'Content-Type': 'application/x-www-form-urlencoded',
|
55 | },
|
56 | });
|
57 |
|
58 | if (!accessToken) {
|
59 | throw Error('Received a bad accessToken!');
|
60 | }
|
61 | this.accessToken = accessToken.data;
|
62 | this.accessToken.createdAt = new Date();
|
63 |
|
64 | if (this.debugTokenFile) {
|
65 | fs.writeFileSync(this.debugTokenFile, JSON.stringify(this.accessToken, null, 2));
|
66 | Log.Debug(`token cached at ${this.debugTokenFile}`);
|
67 | }
|
68 | }
|
69 |
|
70 | |
71 |
|
72 |
|
73 | secondsSinceCreation() {
|
74 | const startDate = new Date(this.accessToken.createdAt);
|
75 | const endDate = new Date();
|
76 | return (endDate.getTime() - startDate.getTime()) / 1000;
|
77 | }
|
78 | }
|
79 |
|
80 | module.exports.SquidexTokenManager = SquidexTokenManager;
|