#20 log-out user in frontend in case of 401 from backend
This commit is contained in:
parent
642062dff2
commit
741874d07d
|
@ -1,11 +1,23 @@
|
||||||
import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
|
import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
|
||||||
import { setContext } from "@apollo/client/link/context";
|
import { setContext } from "@apollo/client/link/context";
|
||||||
import { getRawJsonWebToken } from "../jwt/jwt";
|
import { getRawJsonWebToken, logoutUser } from "../jwt/jwt";
|
||||||
|
import { onError } from "@apollo/client/link/error";
|
||||||
|
import { ServerError } from "@apollo/client/link/utils";
|
||||||
|
import { ServerParseError } from "@apollo/client/link/http";
|
||||||
|
|
||||||
const httpLink = createHttpLink({
|
const httpLink = createHttpLink({
|
||||||
uri: "http://localhost:5433/graphql",
|
uri: "http://localhost:5433/graphql",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const errorLink = onError(({ networkError }) => {
|
||||||
|
if (
|
||||||
|
networkError &&
|
||||||
|
(networkError as ServerError | ServerParseError).statusCode === 401
|
||||||
|
) {
|
||||||
|
logoutUser();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const authLink = setContext((_, { headers }) => {
|
const authLink = setContext((_, { headers }) => {
|
||||||
const token = getRawJsonWebToken();
|
const token = getRawJsonWebToken();
|
||||||
return token
|
return token
|
||||||
|
@ -20,6 +32,6 @@ const authLink = setContext((_, { headers }) => {
|
||||||
|
|
||||||
export const client = new ApolloClient({
|
export const client = new ApolloClient({
|
||||||
cache: new InMemoryCache(),
|
cache: new InMemoryCache(),
|
||||||
link: authLink.concat(httpLink),
|
link: errorLink.concat(authLink.concat(httpLink)),
|
||||||
connectToDevTools: true,
|
connectToDevTools: true,
|
||||||
});
|
});
|
||||||
|
|
|
@ -1,3 +1,5 @@
|
||||||
|
import { client } from "../backend/helper";
|
||||||
|
|
||||||
type UserRole = "candymat_editor" | "candymat_candidate" | "candymat_person";
|
type UserRole = "candymat_editor" | "candymat_candidate" | "candymat_person";
|
||||||
|
|
||||||
interface JwtPayload {
|
interface JwtPayload {
|
||||||
|
@ -47,3 +49,13 @@ export const getJsonWebToken = (): JwtPayload | null => {
|
||||||
const rawToken = getRawJsonWebToken();
|
const rawToken = getRawJsonWebToken();
|
||||||
return rawToken ? parseJwt(rawToken) : null;
|
return rawToken ? parseJwt(rawToken) : null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const logoutUser = async (): Promise<void> => {
|
||||||
|
try {
|
||||||
|
await client.cache.reset();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
location.reload();
|
||||||
|
};
|
||||||
|
|
Loading…
Reference in a new issue