Automatically renew token when znc responds with a token expired error

This commit is contained in:
Samuel Elliott
2022-05-30 12:31:31 +01:00
parent e48fba254c
commit b8f9c2c110
8 changed files with 91 additions and 58 deletions

View File

@@ -1,6 +1,6 @@
import fetch from 'node-fetch';
import fetch, { Response } from 'node-fetch';
import createDebug from 'debug';
import { ActiveEvent, Announcements, CurrentUser, Event, Friend, Presence, PresencePermissions, User, WebService, WebServiceToken, ZncStatus, ZncSuccessResponse } from './znc-types.js';
import { ActiveEvent, Announcements, CurrentUser, Event, Friend, Presence, PresencePermissions, User, WebService, WebServiceToken, ZncErrorResponse, ZncStatus, ZncSuccessResponse } from './znc-types.js';
import { ErrorResponse } from './util.js';
import ZncApi from './znc.js';
import { version } from '../util/product.js';
@@ -12,6 +12,11 @@ const debug = createDebug('nxapi:api:znc-proxy');
export default class ZncProxyApi implements ZncApi {
static useragent: string | null = null;
// Not used by ZncProxyApi
onTokenExpired: ((data: ZncErrorResponse, res: Response) => Promise<void>) | null = null;
/** @internal */
_renewToken: Promise<void> | null = null;
constructor(
private url: string,
// ZncApi uses the NSO token (valid for a few hours)
@@ -139,6 +144,33 @@ export default class ZncProxyApi implements ZncApi {
}
}
export interface AuthToken {
user: string;
policy?: AuthPolicy;
created_at: number;
}
export interface AuthPolicy {
announcements?: boolean;
list_friends?: boolean;
list_friends_presence?: boolean;
friend?: boolean;
friend_presence?: boolean;
webservices?: boolean;
activeevent?: boolean;
current_user?: boolean;
current_user_presence?: boolean;
friends?: string[];
friends_presence?: string[];
}
export enum ZncPresenceEventStreamEvent {
FRIEND_ONLINE = '0',
FRIEND_OFFLINE = '1',
FRIEND_TITLE_CHANGE = '2',
FRIEND_TITLE_STATECHANGE = '3',
}
export type PresenceUrlResponse =
Presence | {presence: Presence} |
CurrentUser | {user: CurrentUser} |

View File

@@ -1,8 +1,8 @@
import fetch from 'node-fetch';
import fetch, { Response } from 'node-fetch';
import { v4 as uuidgen } from 'uuid';
import createDebug from 'debug';
import { f, FlapgIid } from './f.js';
import { AccountLogin, AccountToken, Announcements, CurrentUser, CurrentUserPermissions, Event, Friends, GetActiveEventResult, PresencePermissions, User, WebServices, WebServiceToken, ZncResponse, ZncStatus } from './znc-types.js';
import { AccountLogin, AccountToken, Announcements, CurrentUser, CurrentUserPermissions, Event, Friends, GetActiveEventResult, PresencePermissions, User, WebServices, WebServiceToken, ZncErrorResponse, ZncResponse, ZncStatus, ZncSuccessResponse } from './znc-types.js';
import { getNintendoAccountToken, getNintendoAccountUser, NintendoAccountUser } from './na.js';
import { ErrorResponse } from './util.js';
import { JwtPayload } from '../util/jwt.js';
@@ -20,12 +20,21 @@ export const ZNCA_CLIENT_ID = '71b963c1b7b6d119';
export default class ZncApi {
static useragent: string | null = null;
onTokenExpired: ((data: ZncErrorResponse, res: Response) => Promise<void>) | null = null;
/** @internal */
_renewToken: Promise<void> | null = null;
constructor(
public token: string,
public useragent: string | null = ZncApi.useragent
) {}
async fetch<T = unknown>(url: string, method = 'GET', body?: string, headers?: object) {
async fetch<T = unknown>(
url: string, method = 'GET', body?: string, headers?: object,
/** @internal */ _attempt = 0
): Promise<ZncSuccessResponse<T>> {
await this._renewToken;
const response = await fetch(ZNC_URL + url, {
method: method,
headers: Object.assign({
@@ -42,6 +51,14 @@ export default class ZncApi {
const data = await response.json() as ZncResponse<T>;
if (data.status === ZncStatus.TOKEN_EXPIRED && !_attempt && this.onTokenExpired) {
// _renewToken will be awaited when calling fetch
this._renewToken = this._renewToken ?? this.onTokenExpired.call(null, data, response).finally(() => {
this._renewToken = null;
});
return this.fetch(url, method, body, headers, _attempt + 1);
}
if ('errorMessage' in data) {
throw new ErrorResponse('[znc] ' + data.errorMessage, response, data);
}