Skip to content

Commit 23e04f5

Browse files
authored
Merge pull request #218 from cnblogs/fix-pat-auth
fix: pat authentication
2 parents b4b51ba + e356c69 commit 23e04f5

File tree

2 files changed

+44
-21
lines changed

2 files changed

+44
-21
lines changed

src/auth/auth-manager.ts

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { setCtx } from '@/ctx/global-ctx'
2-
import { authentication, AuthenticationGetSessionOptions as AuthGetSessionOpt, window } from 'vscode'
2+
import { authentication, AuthenticationGetSessionOptions as AuthGetSessionOpt } from 'vscode'
33
import { accountViewDataProvider } from '@/tree-view/provider/account-view-data-provider'
44
import { postDataProvider } from '@/tree-view/provider/post-data-provider'
55
import { postCategoryDataProvider } from '@/tree-view/provider/post-category-tree-data-provider'
@@ -40,26 +40,19 @@ export namespace AuthManager {
4040
}
4141

4242
export async function webLogin() {
43-
const session = await ensureSession({ createIfNone: false, forceNewSession: true })
44-
if (session !== undefined)
45-
await LocalState.setSecret(ExtConst.EXT_SESSION_STORAGE_KEY, JSON.stringify([session]))
43+
authProvider.useBrowser()
44+
await login()
4645
}
4746

4847
export async function patLogin() {
49-
const opt = {
50-
title: '请输入您的个人访问令牌 (PAT)',
51-
prompt: '可通过 https://account.cnblos.com/tokens 获取',
52-
password: true,
53-
}
54-
const pat = await window.showInputBox(opt)
55-
if (pat === undefined) return
48+
authProvider.usePat()
49+
await login()
50+
}
5651

57-
try {
58-
await authProvider.onAccessTokenGranted(pat)
59-
await AuthManager.updateAuthStatus()
60-
} catch (e) {
61-
void Alert.err(`授权失败: ${<string>e}`)
62-
}
52+
export async function login() {
53+
const session = await ensureSession({ createIfNone: false, forceNewSession: true })
54+
if (session !== undefined)
55+
await LocalState.setSecret(ExtConst.EXT_SESSION_STORAGE_KEY, JSON.stringify([session]))
6356
}
6457

6558
export async function logout() {
@@ -86,7 +79,6 @@ export namespace AuthManager {
8679

8780
export async function updateAuthStatus() {
8881
const isAuthed = await AuthManager.isAuthed()
89-
9082
await setCtx('isAuthed', isAuthed)
9183
await setCtx('isUnauthorized', !isAuthed)
9284

src/auth/auth-provider.ts

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { AuthenticationSession as AuthSession } from 'vscode'
1+
import { AuthenticationSession as AuthSession, AuthenticationSession } from 'vscode'
22
import { genVerifyChallengePair } from '@/service/code-challenge'
33
import {
44
authentication,
@@ -48,6 +48,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
4848
readonly providerName = '博客园Cnblogs'
4949

5050
private _allSessions: AuthSession[] = []
51+
private _usePat = false
5152

5253
private readonly _sessionChangeEmitter = new EventEmitter<APASCE>()
5354
private readonly _disposable = Disposable.from(
@@ -64,6 +65,14 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
6465
return this._sessionChangeEmitter.event
6566
}
6667

68+
useBrowser() {
69+
this._usePat = false
70+
}
71+
72+
usePat() {
73+
this._usePat = true
74+
}
75+
6776
async getSessions(scopes?: string[]): Promise<readonly AuthSession[]> {
6877
const sessions = await this.getAllSessions()
6978
const parsedScopes = this.ensureScopes(scopes)
@@ -72,6 +81,25 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
7281
}
7382

7483
createSession(scopes: string[]) {
84+
return this._usePat ? this.createSessionFromPat(scopes) : this.createSessionFromBrowser(scopes)
85+
}
86+
87+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
88+
async createSessionFromPat(scopes: string[]) {
89+
const opt = {
90+
title: '请输入您的个人访问令牌 (PAT)',
91+
prompt: '可通过 https://account.cnblos.com/tokens 获取',
92+
password: true,
93+
validator: (value: string) => (value.length === 0 ? '个人访问令牌(PAT)不能为空' : ''),
94+
}
95+
96+
const pat = await window.showInputBox(opt)
97+
if ((pat ?? '').length === 0) throw new Error('个人访问令牌(PAT)不能为空')
98+
99+
return authProvider.onAccessTokenGranted(pat ?? '')
100+
}
101+
102+
createSessionFromBrowser(scopes: string[]) {
75103
const parsedScopes = this.ensureScopes(scopes)
76104

77105
const cancelTokenSrc = new CancellationTokenSource()
@@ -93,7 +121,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
93121
location: ProgressLocation.Notification,
94122
}
95123

96-
return window.withProgress(options, async (progress, cancelToken) => {
124+
const session = window.withProgress(options, async (progress, cancelToken) => {
97125
progress.report({ message: '等待用户在浏览器中进行授权...' })
98126

99127
cancelToken.onCancellationRequested(() => cancelTokenSrc.cancel())
@@ -136,6 +164,8 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
136164

137165
return fut
138166
})
167+
168+
return session
139169
}
140170

141171
async removeSession(sessionId: string): Promise<void> {
@@ -161,12 +191,13 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
161191

162192
onStateChange?.('即将完成...')
163193

164-
const session = <AuthSession>{
194+
const session = <AuthenticationSession>{
165195
account: accountInfo,
166196
id: `${this.providerId}-${userInfo.space_user_id}`,
167197
accessToken: token,
168198
scopes: this.ensureScopes(null),
169199
}
200+
170201
await LocalState.setSecret(ExtConst.EXT_SESSION_STORAGE_KEY, JSON.stringify([session]))
171202

172203
this._sessionChangeEmitter.fire({

0 commit comments

Comments
 (0)