diff --git a/presenter/renderer/app.ts b/presenter/renderer/app.ts index 49285585be..4362b36d81 100644 --- a/presenter/renderer/app.ts +++ b/presenter/renderer/app.ts @@ -5,11 +5,12 @@ import { createSSRApp, defineComponent, h, markRaw, reactive, Component, provide import PageShell from '#components/PageShell.vue' import { setPageContext } from '#context/usePageContext' -import { apolloClient } from '#plugins/apollo' +import { createApolloClient } from '#plugins/apollo' import i18n from '#plugins/i18n' import pinia from '#plugins/pinia' import CreateVuetify from '#plugins/vuetify' import AuthService from '#src/services/AuthService' +import { useAuthStore } from '#stores/authStore' const vuetify = CreateVuetify(i18n) @@ -18,7 +19,7 @@ function createApp(pageContext: PageContext, isClient = true) { let rootComponent: InstanceType const PageWithWrapper = defineComponent({ setup: () => { - provide(DefaultApolloClient, apolloClient) + provide(DefaultApolloClient, createApolloClient(getToken)) provide('authService', new AuthService()) }, data: () => ({ @@ -52,6 +53,12 @@ function createApp(pageContext: PageContext, isClient = true) { app.use(i18n) app.use(vuetify) + const auth = useAuthStore() + + const getToken = (): string => { + return auth.accessToken + } + objectAssign(app, { changePage: (pageContext: PageContext) => { Object.assign(pageContextReactive, pageContext) diff --git a/presenter/renderer/plugins/apollo.ts b/presenter/renderer/plugins/apollo.ts index 8d86b3c3cd..df8b296d1b 100644 --- a/presenter/renderer/plugins/apollo.ts +++ b/presenter/renderer/plugins/apollo.ts @@ -1,12 +1,24 @@ import { ApolloClient, InMemoryCache } from '@apollo/client/core' +import { setContext } from '@apollo/client/link/context' import { createHttpLink } from '@apollo/client/link/http' // import { onError } from '@apollo/client/link/error' import { ENDPOINTS } from '#src/env' -// HTTP connection to the API +const createAuthLink = (getToken: () => string) => { + return setContext((_, { headers }) => { + const token = getToken() + return { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + headers: { + ...headers, + ...(token && { authorization: `Bearer ${token}` }), + }, + } + }) +} + const httpLink = createHttpLink({ - // You should use an absolute URL here uri: ENDPOINTS.GRAPHQL_URI, }) @@ -23,12 +35,12 @@ const errorLink = onError(({ graphQLErrors, networkError }) => { }) */ -// Cache implementation const cache = new InMemoryCache() -// Create the apollo client -export const apolloClient = new ApolloClient({ - ssrMode: true, - link: httpLink, // errorLink.concat(httpLink), - cache, -}) +export const createApolloClient = (getToken: () => string) => { + return new ApolloClient({ + ssrMode: true, + link: createAuthLink(getToken).concat(httpLink), // errorLink.concat(httpLink), + cache, + }) +}