Skip to content

Commit

Permalink
no longer pass auth token in POST, use cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
artlu99 committed Nov 3, 2024
1 parent 1c98600 commit 02458ac
Show file tree
Hide file tree
Showing 8 changed files with 43 additions and 57 deletions.
48 changes: 19 additions & 29 deletions functions/getSassyHashes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,9 @@ interface SassyHashGraphQLResponse {
getTextByCastHash: SassyHash;
}
interface SassyHashRequest {
privyAuthToken: string;
castHash: string;
}

const getFid = async (context, privyAuthToken: string): Promise<number> => {
const { env, request } = context;
const privy = new PrivyClient(env.REACT_APP_PRIVY_APP_ID, env.PRIVY_APP_SECRET);

const cookie = parse(request.headers.get('Cookie') || '');
const idToken = cookie['privy-id-token'] != null ? cookie['privy-id-token'] : undefined;

const user = await privy.getUser({ idToken });
console.log('privyIdToken:', idToken);
console.log('user:', user);

try {
const verifiedClaims = await privy.verifyAuthToken(privyAuthToken);
const user = await privy.getUser(verifiedClaims.userId);

// const user2 = await privy.getUser({ idToken: IDTokenFromCookies(request) });
return user?.farcaster?.fid;
} catch (error) {
console.error(`Token verification failed with error ${error}.`);
throw new Error('Failed to fetch Farcaster FID');
}
};

const fetchSassyHashExpensiveApi = async (viewerFid: number, castHash: string, env: Env) => {
const client = new Client({
url: env.SASSYHASH_API,
Expand Down Expand Up @@ -72,11 +48,25 @@ const fetchSassyHashExpensiveApi = async (viewerFid: number, castHash: string, e
export const onRequestPost: PagesFunction<Env> = async (context) => {
const { env, request } = context;
const js = (await request.json()) as SassyHashRequest;
const { privyAuthToken, castHash } = js;
const { castHash } = js;

try {
const privy = new PrivyClient(env.REACT_APP_PRIVY_APP_ID, env.PRIVY_APP_SECRET);

const fid = await getFid(context, privyAuthToken);
if (!fid) return new Response(JSON.stringify({ error: 'Failed to fetch Farcaster FID' }), { status: 500 });
const cookie = parse(request.headers.get('Cookie') || '');
const idToken = cookie['privy-id-token'] != null ? cookie['privy-id-token'] : undefined;

const sassyHashResponses = await fetchSassyHashExpensiveApi(fid, castHash, env);
return new Response(JSON.stringify(sassyHashResponses));
const user = await privy.getUser({ idToken });

const fid = user?.farcaster?.fid;
if (fid) {
const sassyHashResponses = await fetchSassyHashExpensiveApi(fid, castHash, env);
return new Response(JSON.stringify(sassyHashResponses));
} else {
return new Response(JSON.stringify({ error: 'Failed to fetch Farcaster FID' }), { status: 500 });
}
} catch (error) {
console.error(`Token verification failed with error ${error}.`);
return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });
}
};
9 changes: 4 additions & 5 deletions src/api/channelFeed.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,22 @@ export interface PagedCronFeed {
}

interface ChannelFeedRequest {
getAccessToken: () => Promise<string | null>;
authenticated: boolean;
channel?: ChannelObject;
pageToken?: string;
following: number[];
}

export const getEnhancedChannelFeed = async (channelFeedRequestPayload: ChannelFeedRequest): Promise<PagedCronFeed> => {
const { channel, getAccessToken, pageToken, following } = channelFeedRequestPayload;
const { channel, authenticated, pageToken, following } = channelFeedRequestPayload;
if (!channel) return { casts: [] };

const privyAuthToken = await getAccessToken();
const cronFeed = await getCronFeed({ channelId: channel.id, pageSize: CHANNEL_FEED_PAGESIZE, pageToken });
const seenFids = sift(cronFeed.casts.map((cast) => cast.author.fid).filter((fid) => fid !== null));
const seenSassyHashes = unique(sift(cronFeed.casts.map((cast) => (isSassy(cast.text) ? cast.hash : null))));
const botOrNotResponse = await getBotOrNot({ fids: seenFids ?? [] });
const sassyHashResponses = privyAuthToken
? await Promise.all(seenSassyHashes.map((sh) => getSassyHash({ privyAuthToken, castHash: sh })))
const sassyHashResponses = authenticated
? await Promise.all(seenSassyHashes.map((sh) => getSassyHash({ castHash: sh })))
: [];

return {
Expand Down
9 changes: 4 additions & 5 deletions src/api/followingFeed.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,22 +39,21 @@ export const getFollowingFeed = (followingFeedRequestPayload: FollowingFeedReque

interface EnhancedFollowingFeedRequest {
fid: number;
getAccessToken: () => Promise<string | null>;
authenticated: boolean;
pageToken?: string;
allChannels: ChannelObject[];
}
export const getEnhancedFollowingFeed = async (
homeFeedRequestPayload: EnhancedFollowingFeedRequest,
): Promise<PagedCronFeed> => {
const { fid, getAccessToken, pageToken, allChannels } = homeFeedRequestPayload;
const { fid, authenticated, pageToken, allChannels } = homeFeedRequestPayload;

const privyAuthToken = await getAccessToken();
const cronFeed = await getFollowingFeed({ fid: fid, pageSize: FOLLOWING_FEED_PAGESIZE, pageToken });
const seenFids = sift(cronFeed.casts.map((cast) => cast.author.fid).filter((fid) => fid !== null));
const seenSassyHashes = unique(sift(cronFeed.casts.map((cast) => (isSassy(cast.text) ? cast.hash : null))));
const botOrNotResponse = await getBotOrNot({ fids: seenFids ?? [] });
const sassyHashResponses = privyAuthToken
? await Promise.all(seenSassyHashes.map((sh) => getSassyHash({ privyAuthToken, castHash: sh })))
const sassyHashResponses = authenticated
? await Promise.all(seenSassyHashes.map((sh) => getSassyHash({ castHash: sh })))
: [];

return {
Expand Down
9 changes: 4 additions & 5 deletions src/api/forYouFeed.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,22 @@ export const getNeynarOpenrankForYouFeed = (forYouFeedRequestPayload: ForYouFeed

interface EnhancedForYouFeedRequest {
fid: number;
getAccessToken: () => Promise<string | null>;
authenticated: boolean;
cursor?: string;
following: number[];
allChannels: ChannelObject[];
}
export const getEnhancedForYouFeed = async (
homeFeedRequestPayload: EnhancedForYouFeedRequest,
): Promise<PagedCronFeed> => {
const { fid, getAccessToken, cursor, following, allChannels } = homeFeedRequestPayload;
const { fid, authenticated, cursor, following, allChannels } = homeFeedRequestPayload;

const privyAuthToken = await getAccessToken();
const forYouFeed = await getNeynarOpenrankForYouFeed({ fid: fid, limit: FORYOU_FEED_PAGESIZE, cursor });
const seenFids = sift(forYouFeed.casts.map((cast) => cast.author.fid).filter((fid) => fid !== null));
const seenSassyHashes = unique(sift(forYouFeed.casts.map((cast) => (isSassy(cast.text) ? cast.hash : null))));
const botOrNotResponse = await getBotOrNot({ fids: seenFids ?? [] });
const sassyHashResponses = privyAuthToken
? await Promise.all(seenSassyHashes.map((sh) => getSassyHash({ privyAuthToken, castHash: sh })))
const sassyHashResponses = authenticated
? await Promise.all(seenSassyHashes.map((sh) => getSassyHash({ castHash: sh })))
: [];

return {
Expand Down
1 change: 0 additions & 1 deletion src/api/sassyHash.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ export interface SassyHashResponse {
data: SassyHash;
}
interface SassyHashRequest {
privyAuthToken: string;
castHash: string;
}

Expand Down
8 changes: 4 additions & 4 deletions src/components/apps/channelFeed/ChannelFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ export const ChannelFeed: React.FC = () => {
return (ffQuery.data?.result?.users ?? [])?.map((u) => Number(u.fid));
}, [ffQuery.isLoading, ffQuery.error, ffQuery.data]);

const { getAccessToken } = usePrivy();
const { authenticated } = usePrivy();

useEffect(() => {
setChannelModerators(unique(sift([activeChannel?.leadFid, activeChannel?.moderatorFid])));
getEnhancedChannelFeed({
getAccessToken,
authenticated,
channel: activeChannel,
following: memodFfData ?? [],
})
Expand All @@ -76,7 +76,7 @@ export const ChannelFeed: React.FC = () => {
.finally(() => {
setLoaded(true);
});
}, [getAccessToken, memodChData, memodFfData, activeChannel]);
}, [authenticated, memodChData, memodFfData, activeChannel]);

useEffect(() => {
setNumCasts(casts.length);
Expand All @@ -97,7 +97,7 @@ export const ChannelFeed: React.FC = () => {

const next = () =>
getEnhancedChannelFeed({
getAccessToken,
authenticated,
channel: activeChannel,
pageToken: nextPageToken,
following: memodFfData ?? [],
Expand Down
8 changes: 4 additions & 4 deletions src/components/apps/followingFeed/FollowingFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ export const FollowingFeed: React.FC<FollowingFeedProps> = ({ fid }) => {
return (ffQuery.data?.result?.users ?? []).map((u) => Number(u.fid));
}, [ffQuery.isLoading, ffQuery.error, ffQuery.data]);

const { getAccessToken } = usePrivy();
const { authenticated } = usePrivy();

useEffect(() => {
setCasts([]);

getEnhancedFollowingFeed({
fid: fid,
getAccessToken,
authenticated,
allChannels: memodChannelData ?? [],
})
.then((res) => {
Expand All @@ -63,7 +63,7 @@ export const FollowingFeed: React.FC<FollowingFeedProps> = ({ fid }) => {
.finally(() => {
setLoaded(true);
});
}, [getAccessToken, fid, memodChannelData, memodFfData]);
}, [authenticated, fid, memodChannelData, memodFfData]);

useEffect(() => {
setNumCasts(casts.length);
Expand All @@ -75,7 +75,7 @@ export const FollowingFeed: React.FC<FollowingFeedProps> = ({ fid }) => {
const next = () =>
getEnhancedFollowingFeed({
fid,
getAccessToken,
authenticated,
pageToken: nextPageToken,
allChannels: memodChannelData ?? [],
}).then((newCasts) => {
Expand Down
8 changes: 4 additions & 4 deletions src/components/apps/forYouFeed/ForYouFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ export const ForYouFeed: React.FC<ForYouFeedProps> = ({ fid }) => {
return (ffQuery.data?.result?.users ?? []).map((u) => Number(u.fid));
}, [ffQuery.isLoading, ffQuery.error, ffQuery.data]);

const { getAccessToken } = usePrivy();
const { authenticated } = usePrivy();

useEffect(() => {
setCasts([]);

getEnhancedForYouFeed({
fid: fid,
getAccessToken,
authenticated,
following: memodFfData ?? [],
allChannels: memodChannelData ?? [],
})
Expand All @@ -66,7 +66,7 @@ export const ForYouFeed: React.FC<ForYouFeedProps> = ({ fid }) => {
.finally(() => {
setLoaded(true);
});
}, [fid, getAccessToken, memodChannelData, memodFfData]);
}, [fid, authenticated, memodChannelData, memodFfData]);

useEffect(() => {
setNumCasts(casts.length);
Expand All @@ -79,7 +79,7 @@ export const ForYouFeed: React.FC<ForYouFeedProps> = ({ fid }) => {
const next = () =>
getEnhancedForYouFeed({
fid: fid,
getAccessToken,
authenticated,
cursor: nextCursor,
following: memodFfData ?? [],
allChannels: memodChannelData ?? [],
Expand Down

0 comments on commit 02458ac

Please sign in to comment.