Skip to content

Commit

Permalink
Add actual logout endpoint to logout method
Browse files Browse the repository at this point in the history
  • Loading branch information
lavgup committed Jan 10, 2021
1 parent 19a81e0 commit 0c26e24
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 11 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
9 changes: 2 additions & 7 deletions src/API.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -17,7 +17,6 @@ export class API {

setServer(url: string): API {
this.url = url;
this.logout();
return this;
}

Expand Down Expand Up @@ -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;
Expand All @@ -75,11 +75,6 @@ export class API {
return body;
}

logout(): void {
this.mwToken = '+\\';
this.jar.removeAllCookiesSync();
}

get(params: Record<string, unknown>, csrf?: boolean): Promise<ResObject> {
return this.mw(params, csrf, 'GET');
}
Expand Down
44 changes: 41 additions & 3 deletions src/MediaWikiJS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
this.api.logout();
async logout(): Promise<ResObject> {
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<string> {
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;
}

/**
Expand Down

0 comments on commit 0c26e24

Please sign in to comment.