a tool for shared writing and social publishing
at feature/analytics 94 lines 3.1 kB view raw
1"use server"; 2 3import { cookies } from "next/headers"; 4import { supabaseServerClient } from "supabase/serverClient"; 5import { cache } from "react"; 6import { deduplicateByUri } from "src/utils/deduplicateRecords"; 7export const getIdentityData = cache(uncachedGetIdentityData); 8export async function uncachedGetIdentityData() { 9 let cookieStore = await cookies(); 10 let auth_token = 11 cookieStore.get("auth_token")?.value || 12 cookieStore.get("external_auth_token")?.value; 13 let auth_res = auth_token 14 ? await supabaseServerClient 15 .from("email_auth_tokens") 16 .select( 17 `*, 18 identities( 19 *, 20 bsky_profiles(*), 21 notifications(count), 22 publication_subscriptions(*), 23 custom_domains!custom_domains_identity_id_fkey(publication_domains(*), *), 24 home_leaflet:permission_tokens!identities_home_page_fkey(*, permission_token_rights(*, 25 entity_sets(entities(facts(*))) 26 )), 27 permission_token_on_homepage( 28 archived, 29 created_at, 30 permission_tokens!inner( 31 id, 32 root_entity, 33 permission_token_rights(*), 34 leaflets_to_documents(*, documents(*)), 35 leaflets_in_publications(*, publications(*), documents(*)) 36 ) 37 ), 38 user_subscriptions(plan, status, current_period_end), 39 user_entitlements(entitlement_key, granted_at, expires_at, source, metadata) 40 )`, 41 ) 42 .eq("identities.notifications.read", false) 43 .eq("id", auth_token) 44 .eq("confirmed", true) 45 .single() 46 : null; 47 if (!auth_res?.data?.identities) return null; 48 49 // Transform embedded entitlements into a keyed record, filtering expired 50 const now = new Date().toISOString(); 51 const entitlements: Record< 52 string, 53 { 54 granted_at: string; 55 expires_at: string | null; 56 source: string | null; 57 metadata: unknown; 58 } 59 > = {}; 60 for (const row of auth_res.data.identities.user_entitlements || []) { 61 if (row.expires_at && row.expires_at < now) continue; 62 entitlements[row.entitlement_key] = { 63 granted_at: row.granted_at, 64 expires_at: row.expires_at, 65 source: row.source, 66 metadata: row.metadata, 67 }; 68 } 69 70 const subscription = auth_res.data.identities.user_subscriptions ?? null; 71 72 if (auth_res.data.identities.atp_did) { 73 //I should create a relationship table so I can do this in the above query 74 let { data: rawPublications } = await supabaseServerClient 75 .from("publications") 76 .select("*") 77 .eq("identity_did", auth_res.data.identities.atp_did); 78 // Deduplicate records that may exist under both pub.leaflet and site.standard namespaces 79 const publications = deduplicateByUri(rawPublications || []); 80 return { 81 ...auth_res.data.identities, 82 publications, 83 entitlements, 84 subscription, 85 }; 86 } 87 88 return { 89 ...auth_res.data.identities, 90 publications: [], 91 entitlements, 92 subscription, 93 }; 94}