Skip to content

Commit a2dfa1a

Browse files
authored
Merge pull request #19 from cnblogs/prompt-login-status-expired
feat: prompt user to relogin if current access token expired
2 parents aa8095a + 3e47339 commit a2dfa1a

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/services/account.service.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import fetch from 'node-fetch';
1010
import { accountViewDataProvider } from '../tree-view-providers/account-view-data-provider';
1111
import { postsDataProvider } from '../tree-view-providers/posts-data-provider';
1212
import { postCategoriesDataProvider } from '../tree-view-providers/categories-view-data-provider';
13+
import { checkIsAccessTokenExpired } from '../utils/check-access-token-expired';
1314

1415
const isAuthorizedStorageKey = 'isAuthorized';
1516

@@ -18,7 +19,12 @@ export class AccountService extends vscode.Disposable {
1819

1920
buildBearerAuthorizationHeader(accessToken?: string): [string, string] {
2021
accessToken ??= this.curUser.authorizationInfo?.accessToken;
21-
return ['Authorization', `Bearer ${accessToken}`];
22+
let expired = checkIsAccessTokenExpired(accessToken!);
23+
if (expired) {
24+
this.logout();
25+
this.alertLoginStatusExpired();
26+
}
27+
return ['Authorization', `Bearer ${expired ? '' : accessToken}`];
2228
}
2329

2430
private _curUser?: UserInfo;
@@ -145,6 +151,18 @@ export class AccountService extends vscode.Disposable {
145151
delete obj.picture;
146152
return Object.assign(new UserInfo(authorizationInfo), obj, { avatar: obj.picture });
147153
}
154+
155+
private async alertLoginStatusExpired() {
156+
const options = ['登录'];
157+
const input = await vscode.window.showInformationMessage(
158+
'登录状态已过期, 请重新登录',
159+
{ modal: true } as vscode.MessageOptions,
160+
...options
161+
);
162+
if (input === options[0]) {
163+
await this.login();
164+
}
165+
}
148166
}
149167

150168
export const accountService = AccountService.instance;
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export const checkIsAccessTokenExpired = (accessToken: string): boolean => {
2+
const decodedText = Buffer.from(accessToken.split('.')[1], 'base64').toString();
3+
let obj: { exp: number } = JSON.parse(decodedText);
4+
let { exp } = obj;
5+
if (!exp) {
6+
throw Error('Invalid accessToken, no exp property');
7+
}
8+
9+
exp *= 1000;
10+
const now = Date.now();
11+
return exp <= now;
12+
};

0 commit comments

Comments
 (0)