UNPKG

2.15 kBJavaScriptView Raw
1const fs = require('fs');
2
3const axios = require('axios');
4const querystring = require('querystring');
5
6const { Log } = require('./logger');
7
8class 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 // Use cache if available
16 if (debugTokenFile && fs.existsSync(debugTokenFile)) {
17 this.accessToken = JSON.parse(fs.readFileSync(debugTokenFile));
18 }
19 }
20
21 /**
22 * Check if the token is valid
23 */
24 isTokenValid() {
25 return this.secondsSinceCreation() < this.accessToken.expires_in;
26 }
27
28 /**
29 * Asynchronous function to retrieve token.
30 */
31 async getToken() {
32 // If don't have token yet trigger the refresh
33 if (!this.accessToken) {
34 await this.refresh();
35 } else if (!this.isTokenValid()) {
36 // We have a token, check it's not expired
37 await this.refresh();
38 }
39 return this.accessToken.access_token;
40 }
41
42 /**
43 * Retrieve a new accessToken for the client and optionally cache it.
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 * Return the number of seconds since the token was cached.
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
80module.exports.SquidexTokenManager = SquidexTokenManager;