#20 log-out user in frontend in case of 401 from backend

This commit is contained in:
Christoph Lienhard 2021-02-07 20:08:41 +01:00
parent 642062dff2
commit 741874d07d
Signed by: christoph.lienhard
GPG Key ID: 6B98870DDC270884
2 changed files with 26 additions and 2 deletions

View File

@ -1,11 +1,23 @@
import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
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({
uri: "http://localhost:5433/graphql",
});
const errorLink = onError(({ networkError }) => {
if (
networkError &&
(networkError as ServerError | ServerParseError).statusCode === 401
) {
logoutUser();
}
});
const authLink = setContext((_, { headers }) => {
const token = getRawJsonWebToken();
return token
@ -20,6 +32,6 @@ const authLink = setContext((_, { headers }) => {
export const client = new ApolloClient({
cache: new InMemoryCache(),
link: authLink.concat(httpLink),
link: errorLink.concat(authLink.concat(httpLink)),
connectToDevTools: true,
});

View File

@ -1,3 +1,5 @@
import { client } from "../backend/helper";
type UserRole = "candymat_editor" | "candymat_candidate" | "candymat_person";
interface JwtPayload {
@ -47,3 +49,13 @@ export const getJsonWebToken = (): JwtPayload | null => {
const rawToken = getRawJsonWebToken();
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();
};