Skip to content
This repository has been archived by the owner on May 13, 2024. It is now read-only.

Commit

Permalink
fix(auth): redirect to login on HTTP 401
Browse files Browse the repository at this point in the history
Until now, a blank screen was shown due to an unhandled exception.
This will redirect to login if the session has timed out.
  • Loading branch information
Akanksh Saxena committed Feb 23, 2022
1 parent eeea6ab commit 45e30e1
Showing 1 changed file with 23 additions and 16 deletions.
39 changes: 23 additions & 16 deletions app/services/ajax.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
* @submodule timed-services
* @public
*/
import { computed } from "@ember/object";
import { reads } from "@ember/object/computed";
import { inject as service } from "@ember/service";
import { isUnauthorizedError } from "ember-ajax/errors";
import AjaxService from "ember-ajax/services/ajax";

/**
Expand All @@ -15,22 +15,17 @@ import AjaxService from "ember-ajax/services/ajax";
* @extends EmberAjax.AjaxService
* @public
*/
export default AjaxService.extend({
/**
* The session service
*
* @property {EmberSimpleAuth.SessionService} session
* @public
*/
session: service("session"),
export default class AjaxCustomService extends AjaxService {
@service session;
@service router;

/**
* The JWT access token.
*
* @property {String} token
* @public
*/
token: reads("session.data.authenticated.access_token"),
@reads("session.data.authenticated.access_token") token;

/**
* The HTTP request headers
Expand All @@ -40,16 +35,28 @@ export default AjaxService.extend({
* @property {Object} headers
* @public
*/
headers: computed("token", function() {
get headers() {
const headers = {
Accept: "application/vnd.api+json",
"Content-Type": "application/vnd.api+json"
};

const auth = this.get("token")
? { Authorization: `Bearer ${this.get("token")}` }
: {};
const auth = this.token ? { Authorization: `Bearer ${this.token}` } : {};

return Object.assign(headers, auth);
})
});
}

handleResponse(status, headers, payload, requestData) {
const response = super.handleResponse(
status,
headers,
payload,
requestData
);

if (isUnauthorizedError(response)) {
this.router.transitionTo("login");
}
return response;
}
}

0 comments on commit 45e30e1

Please sign in to comment.