Skip to content

Commit

Permalink
fix: Fix bug with invalid token file for interactive login (#243)
Browse files Browse the repository at this point in the history
This issue surfaced when trying to do interactive login. It seems like the file was created, but was either invalid or empty. This adds a couple checks to make sure the JSON is parsed correctly and that all the data exists.

Resolves AB#838
  • Loading branch information
tbarlow12 authored Aug 16, 2019
1 parent de798b6 commit 9e3fcac
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
20 changes: 20 additions & 0 deletions src/plugins/login/utils/simpleFileTokenCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,24 @@ describe("Simple File Token Cache", () => {
expect(writeFileSpy).toBeCalledWith(tokenFilePath, JSON.stringify(expected));
writeFileSpy.mockRestore();
});

it("Doesn't fail if unable to parse JSON from file", () => {
mockFs({
"slsTokenCache.json": JSON.stringify(""),
});

const writeFileSpy = jest.spyOn(fs, "writeFileSync");
const testFileCache = new SimpleFileTokenCache(tokenFilePath);
const testSubs = MockFactory.createTestSubscriptions();

testFileCache.addSubs(testSubs);

const expected = {
entries: [],
subscriptions: testSubs,
};

expect(writeFileSpy).toBeCalledWith(tokenFilePath, JSON.stringify(expected));
writeFileSpy.mockRestore();
});
});
21 changes: 13 additions & 8 deletions src/plugins/login/utils/simpleFileTokenCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,26 +64,31 @@ export class SimpleFileTokenCache implements adal.TokenCache {
}

public isEmpty() {
return this.entries.length === 0;
return !this.entries || this.entries.length === 0;
}

public first() {
return this.entries[0];
return (this.entries && this.entries.length) ? this.entries[0] : null;
}

public listSubscriptions() {
return this.subscriptions;
}

private load() {
if (fs.existsSync(this.tokenPath)) {
let savedCache = JSON.parse(fs.readFileSync(this.tokenPath).toString());
this.entries = savedCache.entries;
this.entries.map(t => t.expiresOn = new Date(t.expiresOn))
this.subscriptions = savedCache.subscriptions;
} else {
if (!fs.existsSync(this.tokenPath)) {
this.save();
return;
}
const savedCache = JSON.parse(fs.readFileSync(this.tokenPath).toString());

if (!savedCache || !savedCache.entries) {
this.save();
return;
}
this.entries = savedCache.entries;
this.entries.map(t => t.expiresOn = new Date(t.expiresOn))
this.subscriptions = savedCache.subscriptions;
}

public save() {
Expand Down

0 comments on commit 9e3fcac

Please sign in to comment.