@tsingroc/tsingroc-components 5.0.0-alpha.18 → 5.0.0-alpha.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -175,9 +175,13 @@ interface CommonAuth {
175
175
  logout(redirect?: string): void;
176
176
  /**
177
177
  * 以当前用户的 access token 作为 bearer token 发起请求。
178
- * 用法与正常的 {@linkcode fetch} 完全一致。未登录时,返回的 Promise 会立即失败。
178
+ * 用法与正常的 {@linkcode fetch} 完全一致。未登录时,返回的 Promise 会立即抛出异常。
179
+ * 如果请求返回的状态码是 401,则会自动跳转到登录页。可以使用 `options.redirectOn401`
180
+ * 选项关闭这个行为。
179
181
  */
180
- fetchWithAuth(resource: RequestInfo | URL, options?: RequestInit): Promise<Response>;
182
+ fetchWithAuth(resource: RequestInfo | URL, options?: RequestInit & {
183
+ redirectOn401?: boolean;
184
+ }): Promise<Response>;
181
185
  /** 用户的个人信息,未经过 {@linkcode AuthCheck} 验证时为空。*/
182
186
  userInfo?: UserInfo;
183
187
  /** Access Token,未登录时为空。*/
@@ -19,10 +19,16 @@ const commonAuth = (user, setUser) => ({
19
19
  if (!headers.has("Authorization")) {
20
20
  headers.set("Authorization", `Bearer ${token}`);
21
21
  }
22
- return await fetch(resource, {
22
+ const resp = await fetch(resource, {
23
23
  ...options,
24
24
  headers
25
25
  });
26
+ if ((options?.redirectOn401 ?? true) && resp.status === 401) {
27
+ localStorage.removeItem("access_token");
28
+ setUser({});
29
+ throw new Error("登陆状态无效!");
30
+ }
31
+ return resp;
26
32
  }
27
33
  });
28
34
  function casdoorAuth(user, setUser, sdkConfig, signinOrigin, signinPath) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsingroc/tsingroc-components",
3
- "version": "5.0.0-alpha.18",
3
+ "version": "5.0.0-alpha.19",
4
4
  "author": "",
5
5
  "license": "ISC",
6
6
  "description": "",