import { codeApi } from "@/api/code"; import { create } from "zustand"; export interface OAuthState { active: boolean; clientID: string; redirectURI: string; scope: string[]; state: string; nonce: string; parseSearchParams: (params: URLSearchParams) => void; selectSession: (token: string) => Promise; } export const useOAuth = create((set, get) => ({ active: false, clientID: "", redirectURI: "", scope: [], state: "", nonce: "", parseSearchParams: (params) => { if (get().active) return; set({ active: true, clientID: params.get("client_id") ?? "", redirectURI: params.get("redirect_uri") ?? "", scope: (params.get("scope") ?? "") .trim() .split(" ") .filter((s) => s.length > 0), state: params.get("state") ?? "", nonce: params.get("nonce") ?? "", }); }, selectSession: async (token) => { const { active, redirectURI, nonce, state, clientID } = get(); if (active && redirectURI) { const codeResponse = await codeApi(token, nonce, clientID); const params = new URLSearchParams({ code: codeResponse.code, state, }); window.location.replace(`${redirectURI}?${params.toString()}`); } }, }));