Skip to content
This repository was archived by the owner on Dec 9, 2024. It is now read-only.

fix: Fix bug with invalid token file for interactive login #243

Merged
merged 1 commit into from
Aug 16, 2019
Merged
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
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