Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
lib/*
dist
.idea
17 changes: 14 additions & 3 deletions src/verbs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { StringMap } from "./types";
import { KeratinError } from "./types";
import {StringMap} from "./types";
import {KeratinError} from "./types";
import formData from "./formData";

export function get<T>(url: string, data: StringMap): Promise<T> {
Expand Down Expand Up @@ -33,7 +33,7 @@ function jhr<T>(sender: (xhr: XMLHttpRequest) => void): Promise<T> {
xhr.withCredentials = true; // enable authentication server cookies
xhr.onreadystatechange = () => {
if (xhr.readyState == XMLHttpRequest.DONE) {
const data: {result?: T, errors?: KeratinError[]} = (xhr.responseText.length > 1) ? JSON.parse(xhr.responseText) : {};
const data = maybeParseJSON<T>(xhr.responseText);

if (data.result) {
fulfill(data.result);
Expand All @@ -52,3 +52,14 @@ function jhr<T>(sender: (xhr: XMLHttpRequest) => void): Promise<T> {
sender(xhr);
});
}

function maybeParseJSON<T>(response: string): { result?: T, errors?: KeratinError[] } {
if (response === '') {
return {}
}
try {
return JSON.parse(response)
} catch (err) {
return {errors: [{message: `HTTP response '${response}' is not JSON as expected: ${err}`}]}
}
}
15 changes: 15 additions & 0 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,21 @@ QUnit.test("failure", function(assert) {
});
});

QUnit.test("Non JSON XHR response", function(assert) {
this.server.respondWith('POST', 'https://authn.example.com/session',
'Origin is not a trusted host.'
);

const expectedError = "HTTP response 'Origin is not a trusted host.' is not JSON as expected: SyntaxError: " +
"JSON.parse: unexpected character at line 1 column 1 of the JSON data"

return KeratinAuthN.login({username: 'test', password: 'test'})
.then(refuteSuccess(assert))
.catch(function(errors) {
assert.deepEqual(errors, [{message: expectedError}]);
});
});

QUnit.module("requestPasswordReset", startServer);
QUnit.test("success or failure", function(assert) {
this.server.respondWith('GET', 'https://authn.example.com/password/reset?username=test', '');
Expand Down