Skip to content

Commit

Permalink
feat: Pass in JWT token to the Apollo client
Browse files Browse the repository at this point in the history
* Create a hook that will replace the HTTP link of the Apollog client
to use an authorization token from the Supabase client when we see one
* Update the event-data-provider to call the new hook
* Try to get the Supabase JWT token globally once the Supabase client
  loads
  • Loading branch information
ryscheng committed Mar 19, 2024
1 parent 9999dfa commit 1afcd4a
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 18 deletions.
30 changes: 26 additions & 4 deletions apps/frontend/components/dataprovider/apollo-wrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,41 @@
"use client";

import { ApolloLink, HttpLink } from "@apollo/client";
import { ApolloLink, HttpLink, useApolloClient } from "@apollo/client";
import {
ApolloNextAppProvider,
NextSSRInMemoryCache,
NextSSRApolloClient,
SSRMultipartLink,
} from "@apollo/experimental-nextjs-app-support/ssr";
import { DB_GRAPHQL_URL } from "../../lib/config";
import { userToken } from "../../lib/clients/supabase";

function makeClient() {
// Supabase credentials get populated later on
let initialized = false;
const useEnsureAuth = () => {
const client = useApolloClient();
if (!initialized && userToken) {
client.setLink(makeLink());
initialized = true;
}
};

function makeLink() {
//console.log(userToken);
const httpLink = new HttpLink({
uri: DB_GRAPHQL_URL,
headers: userToken
? {
Authorization: `Bearer ${userToken}`,
}
: {},
});
return httpLink;
}

return new NextSSRApolloClient({
function makeClient() {
const httpLink = makeLink();
const client = new NextSSRApolloClient({
cache: new NextSSRInMemoryCache(),
link:
typeof window === "undefined"
Expand All @@ -26,6 +47,7 @@ function makeClient() {
])
: httpLink,
});
return client;
}

function ApolloWrapper({ children }: React.PropsWithChildren) {
Expand All @@ -36,4 +58,4 @@ function ApolloWrapper({ children }: React.PropsWithChildren) {
);
}

export { ApolloWrapper };
export { ApolloWrapper, useEnsureAuth };
21 changes: 9 additions & 12 deletions apps/frontend/components/dataprovider/event-data-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
CommonDataProviderRegistration,
} from "./provider-view";
import type { CommonDataProviderProps } from "./provider-view";
import { useEnsureAuth } from "./apollo-wrapper";

// Types used in the Plasmic registration
type BucketWidth = "day" | "week" | "month";
Expand Down Expand Up @@ -336,6 +337,7 @@ const formatData = (
* @returns
*/
function ArtifactEventDataProvider(props: EventDataProviderProps) {
useEnsureAuth();
const bucketWidth = getBucketWidth(props);
const query =
bucketWidth === "month"
Expand Down Expand Up @@ -388,9 +390,7 @@ function ArtifactEventDataProvider(props: EventDataProviderProps) {
const formattedData = formatData(props, normalizedEventData, entityData, {
gapFill: bucketWidth === "day",
});
if (!eventLoading) {
console.log(props, rawEventData, eventError, formattedData);
}
!eventLoading && console.log(props, rawEventData, eventError, formattedData);
return (
<DataProviderView
{...props}
Expand All @@ -407,6 +407,7 @@ function ArtifactEventDataProvider(props: EventDataProviderProps) {
* @returns
*/
function ProjectEventDataProvider(props: EventDataProviderProps) {
useEnsureAuth();
const bucketWidth = getBucketWidth(props);
const query =
bucketWidth === "month"
Expand Down Expand Up @@ -454,9 +455,7 @@ function ProjectEventDataProvider(props: EventDataProviderProps) {
const formattedData = formatData(props, normalizedData, entityData, {
gapFill: bucketWidth === "day",
});
if (!eventLoading) {
console.log(props, rawEventData, eventError, formattedData);
}
!eventLoading && console.log(props, rawEventData, eventError, formattedData);
return (
<DataProviderView
{...props}
Expand All @@ -473,6 +472,7 @@ function ProjectEventDataProvider(props: EventDataProviderProps) {
* @returns
*/
function CollectionEventDataProvider(props: EventDataProviderProps) {
useEnsureAuth();
const bucketWidth = getBucketWidth(props);
const query =
bucketWidth === "month"
Expand Down Expand Up @@ -523,9 +523,7 @@ function CollectionEventDataProvider(props: EventDataProviderProps) {
const formattedData = formatData(props, normalizedData, entityData, {
gapFill: bucketWidth === "day",
});
if (!eventLoading) {
console.log(props, rawEventData, eventError, formattedData);
}
!eventLoading && console.log(props, rawEventData, eventError, formattedData);
return (
<DataProviderView
{...props}
Expand All @@ -542,6 +540,7 @@ function CollectionEventDataProvider(props: EventDataProviderProps) {
* @returns
*/
function ProjectUserDataProvider(props: EventDataProviderProps) {
useEnsureAuth();
const {
data: rawEventData,
error: eventError,
Expand Down Expand Up @@ -577,9 +576,7 @@ function ProjectUserDataProvider(props: EventDataProviderProps) {
name: ensure<string>(x.project_name, "project missing 'project_name'"),
}));
const formattedData = formatData(props, normalizedData, entityData);
if (!eventLoading) {
console.log(props, rawEventData, eventError, formattedData);
}
!eventLoading && console.log(props, rawEventData, eventError, formattedData);
return (
<DataProviderView
{...props}
Expand Down
15 changes: 14 additions & 1 deletion apps/frontend/lib/clients/supabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,25 @@ import {
} from "../config";
import { Database } from "../types/supabase";

// Supabase unprivileged client
const supabaseClient = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
// Supabase service account
const supabasePrivileged = createClient<Database>(
SUPABASE_URL,
SUPABASE_SERVICE_KEY,
);

// Get the user JWT token
let userToken: string | undefined;
supabaseClient.auth
.getSession()
.then((data) => {
userToken = data.data.session?.access_token;
})
.catch((e) => {
console.warn("Failed to get Supabase session, ", e);
});

type SupabaseQueryArgs = {
tableName: string; // table to query
columns?: string; // comma-delimited column names (e.g. `address,claimId`)
Expand Down Expand Up @@ -57,5 +70,5 @@ async function supabaseQuery(args: SupabaseQueryArgs): Promise<any[]> {
return data;
}

export { supabaseClient, supabasePrivileged, supabaseQuery };
export { supabaseClient, supabasePrivileged, supabaseQuery, userToken };
export type { SupabaseQueryArgs };
2 changes: 1 addition & 1 deletion apps/frontend/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const DB_GRAPHQL_URL = requireEnv(
"NEXT_PUBLIC_DB_GRAPHQL_URL",
);

export const OSO_API_KEY = process.env.OSO_API_KEY ?? "MISSING";
export const OSO_API_KEY = process.env.OSO_API_KEY;

export const SUPABASE_URL = requireEnv(
process.env.NEXT_PUBLIC_SUPABASE_URL,
Expand Down

0 comments on commit 1afcd4a

Please sign in to comment.