diff --git a/redaktions-app/src/backend/helper.ts b/redaktions-app/src/backend/helper.ts index 7a6dfa3..5e39f32 100644 --- a/redaktions-app/src/backend/helper.ts +++ b/redaktions-app/src/backend/helper.ts @@ -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, }); diff --git a/redaktions-app/src/jwt/jwt.ts b/redaktions-app/src/jwt/jwt.ts index ed8460c..7a5c8ee 100644 --- a/redaktions-app/src/jwt/jwt.ts +++ b/redaktions-app/src/jwt/jwt.ts @@ -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 => { + try { + await client.cache.reset(); + } catch (e) { + console.error(e); + } + localStorage.removeItem("token"); + location.reload(); +};