From 0c26e248d2152f1406ca956976f868946b4c62e5 Mon Sep 17 00:00:00 2001 From: Sidemen19 Date: Sun, 10 Jan 2021 20:50:11 +1100 Subject: [PATCH] Add actual logout endpoint to logout method --- package.json | 2 +- src/API.ts | 9 ++------- src/MediaWikiJS.ts | 44 +++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 44 insertions(+), 11 deletions(-) diff --git a/package.json b/package.json index dd79788..0803d54 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@sidemen19/mediawiki.js", - "version": "4.1.0", + "version": "4.2.0", "description": "A modern wrapper for the MediaWiki API.", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/src/API.ts b/src/API.ts index 4869926..1797760 100644 --- a/src/API.ts +++ b/src/API.ts @@ -5,7 +5,7 @@ import { MediaWikiJSError } from './MediaWikiJSError'; export class API { private mwToken: string; - private readonly jar: CookieJar; + jar: CookieJar; url: string; constructor(options: Config) { @@ -17,7 +17,6 @@ export class API { setServer(url: string): API { this.url = url; - this.logout(); return this; } @@ -62,6 +61,7 @@ export class API { intoken: 'edit', titles: 'F' }); + // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore this.mwToken = Object.values(tokenPack.query.pages)[0].edittoken; @@ -75,11 +75,6 @@ export class API { return body; } - logout(): void { - this.mwToken = '+\\'; - this.jar.removeAllCookiesSync(); - } - get(params: Record, csrf?: boolean): Promise { return this.mw(params, csrf, 'GET'); } diff --git a/src/MediaWikiJS.ts b/src/MediaWikiJS.ts index de6a7fc..5046a43 100644 --- a/src/MediaWikiJS.ts +++ b/src/MediaWikiJS.ts @@ -100,11 +100,49 @@ export class MediaWikiJS { /** * Logs out of a wiki bot. - * API removes cookies and resets mwToken. + * Removes cookies and deletes tokens. */ - async logout(): Promise { - this.api.logout(); + async logout(): Promise { + const token = await this.getCSRFToken(); + const res = await this.api.post({ + action: 'logout', + token + }); + this.api.jar.removeAllCookiesSync(); this.cacheUser = await this.whoAmI(); + + return res; + } + + /** + * Gets a CSRF token. + */ + async getCSRFToken(): Promise { + let tokenPack: ResObject = await this.api.get({ + action: 'query', + meta: 'tokens', + type: 'csrf' + }); + + let token; + + if (tokenPack?.query?.tokens?.csrftoken) { + token = tokenPack.query.tokens.csrftoken; + } else { + // MW 1.19 support + tokenPack = await this.api.get({ + action: 'query', + prop: 'info', + intoken: 'edit', + titles: 'F' + }); + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + token = Object.values(tokenPack.query.pages)[0].edittoken; + } + + return token; } /**