From eb563cb84c10398a1a0a948addad414d8132c0fe Mon Sep 17 00:00:00 2001 From: Randall Morey Date: Fri, 18 Dec 2020 13:28:35 -0500 Subject: [PATCH] =?UTF-8?q?refactor:=20=F0=9F=92=A1=20exract=20token=20val?= =?UTF-8?q?idation=20into=20separate=20method?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- addons/auth/addon/authenticators/password.js | 37 +++++++++----------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/addons/auth/addon/authenticators/password.js b/addons/auth/addon/authenticators/password.js index aa0b13e87..6c793576c 100644 --- a/addons/auth/addon/authenticators/password.js +++ b/addons/auth/addon/authenticators/password.js @@ -36,6 +36,21 @@ import fetch from 'fetch'; export default class PasswordAuthenticator extends BaseAuthenticator { // =methods + /** + * Checks that the given token is valid and resolves, otherwise rejects. + */ + async validateToken(token, tokenID) { + const tokenValidationURL = this.buildTokenValidationEndpointURL(tokenID); + const response = await fetch(tokenValidationURL, { + method: 'get', + headers: { 'Authorization': `Bearer ${token}` } + }); + // 401 and 404 responses mean the token is invalid, whereas other types of + // error responses do not tell us about the validity of the token. + if (response.status === 401 || response.status === 404) return reject(); + return resolve(); + } + /** * Restores the session if data is present and token validation succeeds * (any response other than 401 or 404 === success). Otherwise rejects. @@ -45,26 +60,8 @@ export default class PasswordAuthenticator extends BaseAuthenticator { */ async restore(data) { if (!data) return reject(); - const tokenID = data.id; - const token = data.token; - const tokenValidationURL = this.buildTokenValidationEndpointURL(tokenID); - const response = await fetch(tokenValidationURL, { - method: 'get', - headers: { - // TODO: this is temporary to get the call working, but generating - // the auth header originated in the application authenticator. - // It should probably be factored out into a method on the base. - 'Authorization': `Bearer ${token}` - } - }); - // 401 and 404 responses mean the token is invalid, whereas other types of - // error responses do not tell us about the validity of the token. - switch (response.status) { - case 401: - case 404: - return reject(); - } - return resolve(this.normalizeData(data)); + return this.validateToken(data.token, data.id) + .then(() => this.normalizeData(data)); } /**