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

Commit 9e3fcac

Browse files
authored
fix: Fix bug with invalid token file for interactive login (#243)
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
1 parent de798b6 commit 9e3fcac

File tree

2 files changed

+33
-8
lines changed

2 files changed

+33
-8
lines changed

src/plugins/login/utils/simpleFileTokenCache.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,24 @@ describe("Simple File Token Cache", () => {
8181
expect(writeFileSpy).toBeCalledWith(tokenFilePath, JSON.stringify(expected));
8282
writeFileSpy.mockRestore();
8383
});
84+
85+
it("Doesn't fail if unable to parse JSON from file", () => {
86+
mockFs({
87+
"slsTokenCache.json": JSON.stringify(""),
88+
});
89+
90+
const writeFileSpy = jest.spyOn(fs, "writeFileSync");
91+
const testFileCache = new SimpleFileTokenCache(tokenFilePath);
92+
const testSubs = MockFactory.createTestSubscriptions();
93+
94+
testFileCache.addSubs(testSubs);
95+
96+
const expected = {
97+
entries: [],
98+
subscriptions: testSubs,
99+
};
100+
101+
expect(writeFileSpy).toBeCalledWith(tokenFilePath, JSON.stringify(expected));
102+
writeFileSpy.mockRestore();
103+
});
84104
});

src/plugins/login/utils/simpleFileTokenCache.ts

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,26 +64,31 @@ export class SimpleFileTokenCache implements adal.TokenCache {
6464
}
6565

6666
public isEmpty() {
67-
return this.entries.length === 0;
67+
return !this.entries || this.entries.length === 0;
6868
}
6969

7070
public first() {
71-
return this.entries[0];
71+
return (this.entries && this.entries.length) ? this.entries[0] : null;
7272
}
7373

7474
public listSubscriptions() {
7575
return this.subscriptions;
7676
}
7777

7878
private load() {
79-
if (fs.existsSync(this.tokenPath)) {
80-
let savedCache = JSON.parse(fs.readFileSync(this.tokenPath).toString());
81-
this.entries = savedCache.entries;
82-
this.entries.map(t => t.expiresOn = new Date(t.expiresOn))
83-
this.subscriptions = savedCache.subscriptions;
84-
} else {
79+
if (!fs.existsSync(this.tokenPath)) {
8580
this.save();
81+
return;
8682
}
83+
const savedCache = JSON.parse(fs.readFileSync(this.tokenPath).toString());
84+
85+
if (!savedCache || !savedCache.entries) {
86+
this.save();
87+
return;
88+
}
89+
this.entries = savedCache.entries;
90+
this.entries.map(t => t.expiresOn = new Date(t.expiresOn))
91+
this.subscriptions = savedCache.subscriptions;
8792
}
8893

8994
public save() {

0 commit comments

Comments
 (0)