Skip to content

Commit 1af39a1

Browse files
committed
refactor: update auth
1 parent c5e56a9 commit 1af39a1

File tree

5 files changed

+41
-50
lines changed

5 files changed

+41
-50
lines changed

Diff for: src/auth/access-token.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
export type AccessToken = {
2-
expireTime: number
2+
exp: number
33
}

Diff for: src/auth/account-info.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ export class AccountInfo implements AuthenticationSessionAccountInformation {
77
readonly label: string
88
readonly id: string
99

10-
private _blogApp?: string | null
10+
private _blogApp: string | null = null
1111

1212
private constructor(
1313
public readonly name: string,

Diff for: src/auth/account-manager.ts

+29-36
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,25 @@ import { AlertService } from '@/services/alert.service'
1212

1313
const isAuthorizedStorageKey = 'isAuthorized'
1414

15+
export const ACQUIRE_TOKEN_REJECT_UNAUTHENTICATED = 'unauthenticated'
16+
export const ACQUIRE_TOKEN_REJECT_EXPIRED = 'expired'
17+
1518
class AccountManager extends vscode.Disposable {
16-
// eslint-disable-next-line @typescript-eslint/naming-convention
17-
static readonly ACQUIRE_TOKEN_REJECT_UNAUTHENTICATED = 'unauthenticated'
18-
// eslint-disable-next-line @typescript-eslint/naming-convention
19-
static readonly ACQUIRE_TOKEN_REJECT_EXPIRED = 'expired'
19+
private readonly _authProvider = AuthProvider.instance
20+
private readonly _disposable = Disposable.from(
21+
this._authProvider.onDidChangeSessions(async ({ added }) => {
22+
this._session = null
23+
if (added != null && added.length > 0) await this.ensureSession()
24+
25+
await this.updateAuthorizationStatus()
26+
27+
accountViewDataProvider.fireTreeDataChangedEvent()
28+
postsDataProvider.fireTreeDataChangedEvent(undefined)
29+
postCategoriesDataProvider.fireTreeDataChangedEvent()
2030

21-
private readonly _authProvider: AuthProvider
22-
private readonly _disposable: vscode.Disposable
31+
BlogExportProvider.optionalInstance?.refreshRecords({ force: false, clearCache: true }).catch(console.warn)
32+
})
33+
)
2334

2435
private _oauthClient: OauthApi | null = null
2536
private _session: AuthSession | null = null
@@ -28,26 +39,6 @@ class AccountManager extends vscode.Disposable {
2839
super(() => {
2940
this._disposable.dispose()
3041
})
31-
32-
this._authProvider = AuthProvider.instance
33-
34-
this._disposable = Disposable.from(
35-
this._authProvider,
36-
this._authProvider.onDidChangeSessions(async ({ added }) => {
37-
this._session = null
38-
if (added != null && added.length > 0) await this.ensureSession()
39-
40-
await this.updateAuthorizationStatus()
41-
42-
accountViewDataProvider.fireTreeDataChangedEvent()
43-
postsDataProvider.fireTreeDataChangedEvent(undefined)
44-
postCategoriesDataProvider.fireTreeDataChangedEvent()
45-
46-
BlogExportProvider.optionalInstance
47-
?.refreshRecords({ force: false, clearCache: true })
48-
.catch(console.warn)
49-
})
50-
)
5142
}
5243

5344
get isAuthorized() {
@@ -59,7 +50,8 @@ class AccountManager extends vscode.Disposable {
5950
}
6051

6152
protected get oauthClient() {
62-
return (this._oauthClient ??= new OauthApi())
53+
this._oauthClient ??= new OauthApi()
54+
return this._oauthClient
6355
}
6456

6557
/**
@@ -69,11 +61,12 @@ class AccountManager extends vscode.Disposable {
6961
*/
7062
async acquireToken(): Promise<string> {
7163
const session = await this.ensureSession({ createIfNone: false })
72-
return session == null
73-
? Promise.reject(AccountManager.ACQUIRE_TOKEN_REJECT_UNAUTHENTICATED)
74-
: session.isExpired
75-
? Promise.reject(AccountManager.ACQUIRE_TOKEN_REJECT_EXPIRED)
76-
: session.accessToken
64+
65+
if (session == null) return Promise.reject(ACQUIRE_TOKEN_REJECT_UNAUTHENTICATED)
66+
67+
if (session.isExpired) return Promise.reject(ACQUIRE_TOKEN_REJECT_EXPIRED)
68+
69+
return session.accessToken
7770
}
7871

7972
async login() {
@@ -84,7 +77,7 @@ class AccountManager extends vscode.Disposable {
8477
if (!this.isAuthorized) return
8578

8679
const session = await authentication.getSession(AuthProvider.providerId, [])
87-
if (session) await this._authProvider.removeSession(session.id)
80+
if (session !== undefined) await this._authProvider.removeSession(session.id)
8881

8982
// For old version compatibility, **never** remove this line
9083
await globalContext.storage.update('user', undefined)
@@ -118,9 +111,9 @@ class AccountManager extends vscode.Disposable {
118111
}
119112
}
120113

121-
private async ensureSession(opt?: AuthenticationGetSessionOptions): Promise<AuthSession> {
114+
private async ensureSession(opt?: AuthenticationGetSessionOptions): Promise<AuthSession | null> {
122115
const session = await authentication.getSession(this._authProvider.providerId, [], opt).then(
123-
session => (session ? AuthSession.parse(session) : null),
116+
session => (session ? AuthSession.from(session) : null),
124117
e => AlertService.err(`创建/获取 session 失败: ${e}`)
125118
)
126119

@@ -131,7 +124,7 @@ class AccountManager extends vscode.Disposable {
131124
this._session = session
132125
}
133126

134-
return this._session ?? AuthSession.parse()
127+
return this._session
135128
}
136129
}
137130

Diff for: src/auth/auth-provider.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
7676
const parsedScopes = this.ensureScopes(scopes)
7777

7878
return sessions
79-
.map(x => AuthSession.parse(x))
79+
.map(x => AuthSession.from(x))
8080
.filter(({ scopes: sessionScopes }) => parsedScopes.every(x => sessionScopes.includes(x)))
8181
}
8282

@@ -179,7 +179,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
179179
| null
180180
| undefined
181181
| unknown
182-
this._allSessions = isArray(sessions) ? sessions.map(x => AuthSession.parse(x)) : []
182+
this._allSessions = isArray(sessions) ? sessions.map(x => AuthSession.from(x)) : []
183183
}
184184

185185
return this._allSessions
@@ -250,7 +250,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
250250
session = ifNotCancelledThen(() => {
251251
if (isUndefined(spec)) return
252252

253-
return AuthSession.parse({
253+
return AuthSession.from({
254254
accessToken,
255255
refreshToken,
256256
account: AccountInfo.from(spec),

Diff for: src/auth/session.ts

+7-9
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,16 @@ export class AuthSession implements AuthenticationSession {
1515
) {}
1616

1717
get isExpired() {
18-
if (this._parsedAccessToken === null) return true
19-
return this._parsedAccessToken.expireTime * 1000 <= Date.now()
20-
}
21-
22-
private get parsedAccessToken() {
23-
const buf = Buffer.from(this.accessToken.split('.')[1], 'base64')
24-
this._parsedAccessToken ??= JSON.parse(buf.toString())
18+
if (this._parsedAccessToken == null) {
19+
const buf = Buffer.from(this.accessToken.split('.')[1], 'base64')
20+
this._parsedAccessToken ??= JSON.parse(buf.toString())
21+
}
2522

26-
return this._parsedAccessToken
23+
if (this._parsedAccessToken == null) return true
24+
return this._parsedAccessToken.exp * 1000 <= Date.now()
2725
}
2826

29-
static parse<T extends AuthenticationSession | Partial<AuthSession>>(t?: T) {
27+
static from<T extends AuthenticationSession | Partial<AuthSession>>(t?: T) {
3028
const session = new AuthSession(AccountInfo.newAnonymous())
3129

3230
merge(session, pick(t, keys(session)))

0 commit comments

Comments
 (0)