Skip to content

Commit d64751c

Browse files
authored
Merge pull request #222 from cnblogs/fix-sign-in
fix: sign in without blog
2 parents 411e6fc + a133785 commit d64751c

14 files changed

+116
-69
lines changed

src/auth/auth-manager.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { BlogExportProvider } from '@/tree-view/provider/blog-export-provider'
1010
import { Alert } from '@/infra/alert'
1111
import { LocalState } from '@/ctx/local-state'
1212
import { ExtConst } from '@/ctx/ext-const'
13-
import { UserService } from '@/service/user-info'
13+
import { UserService } from '@/service/user.service'
1414
import { isAuthSessionExpired } from '@/auth/is-auth-session-expired'
1515

1616
authProvider.onDidChangeSessions(async () => {
@@ -60,11 +60,12 @@ export namespace AuthManager {
6060

6161
try {
6262
const session = await authentication.getSession(authProvider.providerId, [])
63-
if (session === undefined) return
63+
if (session == null) return
6464
await Oauth.revokeToken(session.accessToken)
6565
await authProvider.removeSession(session.id)
6666
} catch (e) {
6767
void Alert.err(`登出发生错误: ${<string>e}`)
68+
throw e
6869
}
6970
}
7071

@@ -84,10 +85,10 @@ export namespace AuthManager {
8485

8586
if (!isAuthed) return
8687

87-
const userInfo = await UserService.getInfo()
88-
if (userInfo !== undefined) {
88+
const userInfo = await UserService.getUserInfo()
89+
if (userInfo !== null) {
8990
await setCtx('user', {
90-
name: userInfo.display_name,
91+
name: userInfo.displayName,
9192
avatar: userInfo.avatar,
9293
})
9394
}

src/auth/auth-provider.ts

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import { RsRand } from '@/wasm'
2020
import { Alert } from '@/infra/alert'
2121
import { LocalState } from '@/ctx/local-state'
2222
import { ExtConst } from '@/ctx/ext-const'
23-
import { UserService } from '@/service/user-info'
23+
import { UserService } from '@/service/user.service'
2424

2525
async function browserSignIn(challengeCode: string, scopes: string[]) {
2626
const para = consUrlPara(
@@ -96,7 +96,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
9696
const pat = await window.showInputBox(opt)
9797
if ((pat ?? '').length === 0) throw new Error('个人访问令牌(PAT)不能为空')
9898

99-
return authProvider.onAccessTokenGranted(pat ?? '')
99+
return authProvider.onAccessTokenGranted(pat ?? '', true)
100100
}
101101

102102
createSessionFromBrowser(scopes: string[]) {
@@ -145,7 +145,7 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
145145

146146
try {
147147
const token = await Oauth.getToken(verifyCode, authCode)
148-
const authSession = await this.onAccessTokenGranted(token, state =>
148+
const authSession = await this.onAccessTokenGranted(token, false, state =>
149149
progress.report({ message: state })
150150
)
151151

@@ -182,18 +182,29 @@ export class AuthProvider implements AuthenticationProvider, Disposable {
182182
this._sessionChangeEmitter.fire({ removed: data.remove, added: undefined, changed: undefined })
183183
}
184184

185-
async onAccessTokenGranted(token: string, onStateChange?: (state: string) => void) {
185+
async onAccessTokenGranted(token: string, isPat: boolean, onStateChange?: (state: string) => void) {
186186
onStateChange?.('正在获取账户信息...')
187187

188-
const userInfo = await UserService.getInfoWithToken(token)
189-
if (userInfo === undefined) throw Error('用户信息获取失败')
190-
const accountInfo = { id: userInfo.space_user_id.toString(), label: userInfo.display_name }
188+
const userInfo = await UserService.getUserInfoWithToken(token, isPat)
189+
if (userInfo == null) {
190+
const errorMsg = '获取用户信息失败: userInfo is null'
191+
void Alert.warn
192+
throw Error(errorMsg)
193+
}
194+
195+
if (userInfo.blogApp == null)
196+
void Alert.warn('您的账号未开通博客,[立即开通](https://account.cnblogs.com/blog-apply)')
191197

192198
onStateChange?.('即将完成...')
193199

200+
const { accountId, displayName } = userInfo
201+
194202
const session = <AuthenticationSession>{
195-
account: accountInfo,
196-
id: `${this.providerId}-${userInfo.space_user_id}`,
203+
account: {
204+
id: new Number(accountId).toString(),
205+
label: displayName,
206+
},
207+
id: `${this.providerId}-${userInfo.accountId}`,
197208
accessToken: token,
198209
scopes: this.ensureScopes(null),
199210
}

src/cmd/browser.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Uri } from 'vscode'
22
import { execCmd } from '@/infra/cmd'
3-
import { UserService } from '@/service/user-info'
3+
import { UserService } from '@/service/user.service'
4+
import { Alert } from '@/infra/alert'
45

56
export namespace Browser.Open {
67
export function open(url: string) {
@@ -19,14 +20,17 @@ export namespace Browser.Open.User {
1920
export const accountSetting = () => open('https://account.cnblogs.com/settings/account')
2021

2122
export async function blog() {
22-
const blogApp = (await UserService.getInfo())?.blog_app
23-
if (blogApp !== undefined) void open(`https://www.cnblogs.com/${blogApp}`)
23+
const blogApp = (await UserService.getUserInfo())?.blogApp
24+
25+
if (blogApp == null) return void Alert.warn('未开通博客')
26+
27+
void open(`https://www.cnblogs.com/${blogApp}`)
2428
}
2529

2630
export const blogConsole = () => open('https://i.cnblogs.com')
2731

2832
export async function home() {
29-
const accountId = (await UserService.getInfo())?.space_user_id
33+
const accountId = (await UserService.getUserInfo())?.accountId
3034
if (accountId !== undefined) {
3135
const url = `https://home.cnblogs.com/u/${accountId}`
3236
return open(url)

src/cmd/pdf/export-pdf.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { PostTreeItem } from '@/tree-view/model/post-tree-item'
1313
import { PostEditDto } from '@/model/post-edit-dto'
1414
import { PostPdfTemplateBuilder } from '@/cmd/pdf/post-pdf-template-builder'
1515
import { ChromiumCfg } from '@/ctx/cfg/chromium'
16-
import { UserService } from '@/service/user-info'
16+
import { UserService } from '@/service/user.service'
1717

1818
async function launchBrowser(chromiumPath: string) {
1919
try {
@@ -170,8 +170,11 @@ export async function exportPostToPdf(input?: Post | PostTreeItem | Uri): Promis
170170
const chromiumPath = await retrieveChromiumPath()
171171
if (chromiumPath === undefined) return
172172

173-
const blogApp = (await UserService.getInfo())?.blog_app
174-
if (blogApp === undefined) return void Alert.warn('无法获取博客地址, 请检查登录状态')
173+
const userInfo = await UserService.getUserInfo()
174+
if (userInfo == null) return void Alert.warn('用户不存在')
175+
176+
const blogApp = userInfo.blogApp
177+
if (blogApp == null) return void Alert.warn('未开通博客')
175178

176179
await window.withProgress<string[] | undefined>(
177180
{

src/cmd/pdf/post-pdf-template-builder.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { BlogSettingService } from '@/service/blog-setting'
55
import { PostCatService } from '@/service/post/post-cat'
66
import { PostCat } from '@/model/post-cat'
77
import { markdownItFactory } from '@cnblogs/markdown-it-presets'
8-
import { UserService } from '@/service/user-info'
8+
import { UserService } from '@/service/user.service'
99

1010
export namespace PostPdfTemplateBuilder {
1111
export const HighlightedMessage = 'markdown-highlight-finished'
@@ -66,7 +66,7 @@ export namespace PostPdfTemplateBuilder {
6666
blogId,
6767
} = setting
6868

69-
const userId = (await UserService.getInfo())?.user_id
69+
const userId = (await UserService.getUserInfo())?.userId
7070

7171
return `<html lang="en">
7272
<head>

src/cmd/post-list/post-list-view.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { PostListState } from '@/model/post-list-state'
66
import { extTreeViews } from '@/tree-view/tree-view-register'
77
import { PageList } from '@/model/page'
88
import { getListState, updatePostListState } from '@/service/post/post-list-view'
9+
import { UserService } from '@/service/user.service'
910

1011
let refreshTask: Promise<boolean> | null = null
1112
let isLoading = false
@@ -75,8 +76,8 @@ export namespace PostListView {
7576

7677
refreshTask = fut()
7778
.then(() => true)
78-
.catch(e => {
79-
void Alert.err(`刷新随笔列表失败: ${<string>e}`)
79+
.catch(async e => {
80+
if (await UserService.hasBlog()) void Alert.err(`刷新随笔列表失败: ${<string>e}`)
8081
return false
8182
})
8283
.finally(() => (refreshTask = null))

src/cmd/post-list/post-pull-all.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { PostFileMapManager } from '@/service/post/post-file-map'
44
import { basename } from 'path'
55
import { ProgressLocation, Uri, window, workspace } from 'vscode'
66
import { buildLocalPostFileUri } from '@/cmd/post-list/open-post-in-vscode'
7-
import { UserService } from '@/service/user-info'
7+
import { UserService } from '@/service/user.service'
88
import { fsUtil } from '@/infra/fs/fsUtil'
99

1010
enum ConflictStrategy {
@@ -27,7 +27,7 @@ const MAX_BYTE_LIMIT = MAX_POST_LIMIT * 1024 * 20
2727
const MAX_MB_LIMIT = Math.round(MAX_BYTE_LIMIT / 1024 / 1024)
2828

2929
export async function postPullAll() {
30-
const isVip = (await UserService.getInfo())?.is_vip ?? false
30+
const isVip = (await UserService.getUserInfo())?.isVip ?? false
3131
if (!isVip) {
3232
void Alert.info('下载随笔: 您是普通用户, 此功能目前仅面向 [VIP](https://cnblogs.vip/) 用户开放')
3333
return

src/model/user-info.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export interface UserInfo {
2+
userId: string
3+
accountId: number
4+
displayName: string
5+
blogApp: string
6+
avatar: string
7+
isVip: boolean
8+
}

src/service/post/post-cat.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Alert } from '@/infra/alert'
33
import { SiteCat } from '@/model/site-category'
44
import { AuthManager } from '@/auth/auth-manager'
55
import { PostCatReq, Token } from '@/wasm'
6+
import { UserService } from '../user.service'
67

78
// TODO: need better cache impl
89
let siteCategoryCache: SiteCat[] | null = null
@@ -22,7 +23,7 @@ export namespace PostCatService {
2223
const { categories } = <{ categories: PostCat[] }>JSON.parse(resp)
2324
return categories.map(x => Object.assign(new PostCat(), x))
2425
} catch (e) {
25-
void Alert.err(`查询随笔分类失败: ${<string>e}`)
26+
if (await UserService.hasBlog()) void Alert.err(`查询随笔分类失败: ${<string>e}`)
2627
throw e
2728
}
2829
}
@@ -34,7 +35,7 @@ export namespace PostCatService {
3435
const { parent } = <{ parent: PostCat | null }>JSON.parse(resp)
3536
return Object.assign(new PostCat(), parent)
3637
} catch (e) {
37-
void Alert.err(`查询随笔分类失败: ${<string>e}`)
38+
if (await UserService.hasBlog()) void Alert.err(`查询随笔分类失败: ${<string>e}`)
3839
throw e
3940
}
4041
}
@@ -46,7 +47,7 @@ export namespace PostCatService {
4647
const { categories } = <{ categories: PostCat[] }>JSON.parse(resp)
4748
return categories.map(x => Object.assign(new PostCat(), x))
4849
} catch (e) {
49-
void Alert.err(`查询随笔分类失败: ${<string>e}`)
50+
if (await UserService.hasBlog()) void Alert.err(`查询随笔分类失败: ${<string>e}`)
5051
throw e
5152
}
5253
}

src/service/user-info.ts

Lines changed: 0 additions & 33 deletions
This file was deleted.

src/service/user.service.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { Alert } from '@/infra/alert'
2+
import { AuthManager } from '@/auth/auth-manager'
3+
import { UserInfo } from '@/model/user-info'
4+
import { ExtConst } from '@/ctx/ext-const'
5+
6+
export namespace UserService {
7+
export async function getUserInfo(): Promise<UserInfo> {
8+
const token = await AuthManager.acquireToken()
9+
// TODO: need better solution
10+
const isPatToken = token.length === 64
11+
return getUserInfoWithToken(token, isPatToken)
12+
}
13+
14+
export async function hasBlog(): Promise<boolean> {
15+
const userInfo = await UserService.getUserInfo()
16+
return userInfo?.blogApp != null
17+
}
18+
19+
export async function getUserInfoWithToken(token: string, isPat: boolean): Promise<UserInfo> {
20+
const url = `${ExtConst.ApiBase.OPENAPI}/users/v2`
21+
22+
const headers = new Headers()
23+
headers.append('authorization', `Bearer ${token}`)
24+
headers.append('content-type', 'application/json')
25+
if (isPat) headers.append('authorization-type', 'pat')
26+
27+
const req = await fetch(url, {
28+
headers: {
29+
authorization: `Bearer ${token}`,
30+
'content-type': 'application/json',
31+
'authorization-type': isPat ? 'pat' : '',
32+
},
33+
})
34+
35+
if (!req.ok) {
36+
const message = `${req.status}: ${req.statusText}`
37+
void Alert.err(`获取用户信息失败: ${message}`)
38+
throw new Error(message)
39+
}
40+
41+
const userInfo = (await req.json()) as UserInfo
42+
43+
if (userInfo.userId == null) void Alert.err(`获取用户信息失败: userId is null`)
44+
45+
if (userInfo.accountId === undefined) void Alert.err(`获取用户信息失败: accountId is undefined`)
46+
47+
return userInfo
48+
}
49+
}

src/tree-view/provider/account-view-data-provider.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { AuthManager } from '@/auth/auth-manager'
22
import { EventEmitter, ThemeIcon, TreeDataProvider, TreeItem } from 'vscode'
3-
import { UserService } from '@/service/user-info'
3+
import { UserService } from '@/service/user.service'
44

55
export class AccountViewDataProvider implements TreeDataProvider<TreeItem> {
66
protected _onDidChangeTreeData = new EventEmitter<null | undefined>()
@@ -16,7 +16,7 @@ export class AccountViewDataProvider implements TreeDataProvider<TreeItem> {
1616
async getChildren(el?: TreeItem) {
1717
if (!(await AuthManager.isAuthed()) || el !== undefined) return []
1818

19-
const userName = (await UserService.getInfo())?.display_name
19+
const userName = (await UserService.getUserInfo())?.displayName
2020
return [
2121
{ label: userName, tooltip: '用户名', iconPath: new ThemeIcon('account') },
2222
{
@@ -53,7 +53,6 @@ export class AccountViewDataProvider implements TreeDataProvider<TreeItem> {
5353
},
5454
{
5555
label: '退出登录',
56-
tooltip: '',
5756
command: {
5857
title: '退出登录',
5958
command: 'vscode-cnb.logout',

src/tree-view/provider/blog-export-provider.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
import { Event, EventEmitter, ProviderResult, TreeDataProvider, TreeItem } from 'vscode'
1515
import { Alert } from '@/infra/alert'
1616
import { BlogExportRecord } from '@/model/blog-export'
17+
import { UserService } from '@/service/user.service'
1718

1819
export class BlogExportProvider implements TreeDataProvider<BlogExportTreeItem> {
1920
private static _instance: BlogExportProvider | null = null
@@ -111,8 +112,9 @@ export class BlogExportProvider implements TreeDataProvider<BlogExportTreeItem>
111112
const hasCacheRefreshed = force
112113
? await BlogExportRecordsStore?.refresh()
113114
.then(() => true)
114-
.catch(e => {
115-
if (notifyOnError) void Alert.err(`刷新备份记录失败: ${<string>e}`)
115+
.catch(async e => {
116+
if (notifyOnError && (await UserService.hasBlog()))
117+
void Alert.err(`刷新备份记录失败: ${<string>e}`)
116118
return false
117119
})
118120
: clearCache

src/tree-view/provider/post-data-provider.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { PostTreeItem } from '@/tree-view/model/post-tree-item'
99
import { PostListCfg } from '@/ctx/cfg/post-list'
1010
import { Page, PageList } from '@/model/page'
1111
import { PostListView } from '@/cmd/post-list/post-list-view'
12+
import { UserService } from '@/service/user.service'
1213

1314
export type PostListTreeItem = Post | PostTreeItem | TreeItem | PostMetadata | PostSearchResultEntry
1415

@@ -69,7 +70,7 @@ export class PostDataProvider implements TreeDataProvider<PostListTreeItem> {
6970

7071
return this.page
7172
} catch (e) {
72-
void Alert.err(`加载博文失败: ${<string>e}`)
73+
if (await UserService.hasBlog()) void Alert.err(`加载博文失败: ${<string>e}`)
7374
throw e
7475
}
7576
}

0 commit comments

Comments
 (0)