File size: 1,866 Bytes
b387e01
 
4c5fda9
 
 
 
 
 
 
 
 
 
b387e01
 
 
 
430efad
4c5fda9
 
 
 
 
 
b387e01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c5fda9
 
 
 
b387e01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { createClient, type Session, type SupabaseClient } from "@supabase/supabase-js";

export type PlanCard = {
  id: string;
  name: string;
  daily_rewrites: number;
  max_words_per_request: number;
  daily_word_cap: number;
  price_inr_monthly: number;
  blurb?: string;
};

export type AuthConfig = {
  enabled: boolean;
  supabase_url: string;
  supabase_anon_key: string;
  session_idle_minutes?: number;
  guest?: {
    daily_rewrites: number;
    max_words_per_request: number;
    daily_word_cap: number;
  };
  plans?: PlanCard[];
};

let client: SupabaseClient | null = null;
let cachedConfig: AuthConfig | null = null;

export async function loadAuthConfig(): Promise<AuthConfig> {
  if (cachedConfig) return cachedConfig;
  const res = await fetch("/v1/auth/config");
  if (!res.ok) {
    cachedConfig = { enabled: false, supabase_url: "", supabase_anon_key: "" };
    return cachedConfig;
  }
  cachedConfig = (await res.json()) as AuthConfig;
  return cachedConfig;
}

export function getCachedAuthConfig(): AuthConfig | null {
  return cachedConfig;
}

export function getSupabase(): SupabaseClient | null {
  return client;
}

export async function initSupabase(): Promise<AuthConfig> {
  const config = await loadAuthConfig();
  if (config.enabled && config.supabase_url && config.supabase_anon_key) {
    client = createClient(config.supabase_url, config.supabase_anon_key, {
      auth: {
        persistSession: true,
        autoRefreshToken: true,
        detectSessionInUrl: true,
      },
    });
  } else {
    client = null;
  }
  return config;
}

export async function getAccessToken(): Promise<string | null> {
  if (!client) return null;
  const { data } = await client.auth.getSession();
  return data.session?.access_token ?? null;
}

export type { Session };