Skip to content

Commit 335111d

Browse files
authored
Merge pull request #1365 from chhsiao1981/401-redirect
add 401-redirect
2 parents e514d98 + 1660700 commit 335111d

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/api/api.ts

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import config from "config";
22
import { Cookies } from "react-cookie";
3+
import { STATUS_UNAUTHORIZED } from "./constants";
34

45
export type Query = Record<string, any>;
56

@@ -100,8 +101,6 @@ const callApi = async <T>(
100101
API_ROOT = API_ROOT.slice(0, API_ROOT.length - 1);
101102
}
102103

103-
console.info("api.api: API_ROOT:", API_ROOT, "paramsAPIRoot:", paramsAPIRoot);
104-
105104
let theEndpoint = endpoint;
106105
if (!theEndpoint.includes(API_ROOT)) {
107106
theEndpoint = `${API_ROOT}${endpoint}`;
@@ -166,6 +165,29 @@ const postFile = async <T>(
166165
);
167166
};
168167

168+
const getCurrentPathQeury = () => {
169+
const searchStr = getCurrentPathQeurySanitizeSearch(window.location.search);
170+
return `${window.location.pathname}${searchStr}`;
171+
};
172+
173+
const getCurrentPathQeurySanitizeSearch = (search: string) => {
174+
if (!search) {
175+
return "";
176+
}
177+
178+
// if with only '?': remove '?'
179+
if (search[0] === "?" && search.length === 1) {
180+
return "";
181+
}
182+
183+
// if not starting with '?': add '?'
184+
if (search[0] !== "?") {
185+
return `?${search}`;
186+
}
187+
188+
return search;
189+
};
190+
169191
const fetchCore = async <T>(
170192
endpoint: string,
171193
options: RequestInit,
@@ -177,6 +199,11 @@ const fetchCore = async <T>(
177199
return res
178200
.json()
179201
.then((collectionJsonData) => {
202+
if (res.status === STATUS_UNAUTHORIZED) {
203+
const redirectTo = encodeURIComponent(getCurrentPathQeury());
204+
window.location.href = `/login?redirectTo=${redirectTo}`;
205+
}
206+
180207
if (res.status >= 400) {
181208
const msg = collectionJsonData.error;
182209
return { status, errmsg: msg };

src/api/constants.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
11
export const STATUS_OK = 200;
22
export const STATUS_OK_CREATE = 201;
33
export const STATUS_OK_EMPTY = 204;
4+
export const STATUS_UNAUTHORIZED = 401;
5+
export const STATUS_FORBIDDEN = 403;
6+
export const STATUS_NOT_FOUND = 404;
7+
export const STATUS_ERROR = 500;

0 commit comments

Comments
 (0)