/** * Settings → API Access (3.3): API keys for Yatra's REST API. * * Keys are WordPress application passwords made for a chosen user; a key * can do what that user can. The plain key is shown once. */ import React, { useState } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { KeyRound, Trash2, Copy, AlertTriangle } from "lucide-react"; import { __, sprintf } from "../../lib/i18n"; import { apiClient } from "../../lib/api-client"; import { formatDate } from "../../lib/dateFormat"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { Label } from "../ui/label"; import { Select } from "../ui/select"; interface ApiKey { uuid: string; name: string; user_id: number; user: string; created: string | null; last_used: string | null; } interface Props { /** Keep the Settings page's own copy in step, so its Save doesn't post the old value back. */ onSettingSaved?: (key: string, value: unknown) => void; } const ApiAccessSection: React.FC = ({ onSettingSaved }) => { const queryClient = useQueryClient(); const [name, setName] = useState(""); const [userId, setUserId] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const [created, setCreated] = useState<{ name: string; user: string; password: string } | null>(null); const [copied, setCopied] = useState(false); const q = useQuery({ queryKey: ["api-keys"], queryFn: async () => await apiClient.get("/api-keys"), }); // Embed trips on other websites. const [embedTrips, setEmbedTrips] = useState([]); const [embedLimit, setEmbedLimit] = useState("6"); const [embedColumns, setEmbedColumns] = useState("3"); const [embedSaving, setEmbedSaving] = useState(false); const [embedOn, setEmbedOn] = useState(null); const embedTripsQuery = useQuery({ queryKey: ["embed-trips"], queryFn: async () => { const res: any = await apiClient.get("/trips", { params: { per_page: 100, status: "publish" } }); const items: any[] = res?.data?.data || res?.data || res || []; return Array.isArray(items) ? items : []; }, }); const snippetQuery = useQuery({ queryKey: ["embed-snippet", embedTrips.join(","), embedLimit, embedColumns], queryFn: async () => await apiClient.get("/embed/snippet", { params: { trips: embedTrips.join(","), limit: embedLimit, columns: embedColumns }, }), }); const snippet: any = snippetQuery.data || {}; const toggleEmbed = async (on: boolean) => { setEmbedSaving(true); setEmbedOn(on); try { await apiClient.post("/settings", { embed_enabled: on }); onSettingSaved?.("embed_enabled", on); queryClient.invalidateQueries({ queryKey: ["embed-snippet"] }); } catch (e: any) { setEmbedOn(!on); setError(e?.message || __("Could not save.", "yatra")); } finally { setEmbedSaving(false); } }; const data: any = q.data || {}; const keys: ApiKey[] = data.keys || []; const users: Array<{ id: number; login: string; name: string; is_admin: boolean }> = data.users || []; const chosen = users.find((u) => String(u.id) === userId); const create = async () => { setBusy(true); setError(""); try { const res: any = await apiClient.post("/api-keys", { name, user_id: userId ? parseInt(userId, 10) : undefined }); setCreated(res.key); setName(""); setCopied(false); queryClient.invalidateQueries({ queryKey: ["api-keys"] }); } catch (e: any) { setError(e?.message || __("Could not create the key.", "yatra")); } finally { setBusy(false); } }; const revoke = async (k: ApiKey) => { if (!window.confirm(sprintf(__("Revoke \"%s\"? Apps using it stop working at once.", "yatra"), k.name))) { return; } try { await apiClient.delete(`/api-keys/${k.user_id}/${k.uuid}`); queryClient.invalidateQueries({ queryKey: ["api-keys"] }); } catch (e: any) { setError(e?.message || __("Could not revoke the key.", "yatra")); } }; if (q.isLoading) { return

{__("Loading…", "yatra")}

; } return (

{__( "API keys let another app (a booking channel, your CRM, Zapier/Make via HTTP) use Yatra's REST API. A key works as the user it belongs to, with that user's permissions — make keys for a dedicated user with a Yatra staff role, not for an administrator.", "yatra", )}

{__("Send the key with HTTP Basic auth: user name + key. Example:", "yatra")}{" "} {`curl -u "USER:KEY" ${data.rest_base || "/wp-json/yatra/v1/"}bookings`}

{!data.available && (

{__("WordPress application passwords are off on this site. They need HTTPS (or a plugin may have turned them off).", "yatra")}

)} {created && (

{sprintf(__("Key \"%1$s\" for %2$s — copy it now, it won't be shown again:", "yatra"), created.name, created.user)}

{created.password}
)} {data.available && (
setName(e.target.value)} />
{(chosen ? chosen.is_admin : true) && (

{__("This user is an administrator: the key could change anything on the site. Prefer a user with a Yatra staff role.", "yatra")}

)}
)} {error &&

{error}

}

{__("Keys", "yatra")}

{keys.length === 0 ? (

{__("No API keys yet.", "yatra")}

) : ( {keys.map((k) => ( ))}
{__("Name", "yatra")} {__("User", "yatra")} {__("Created", "yatra")} {__("Last used", "yatra")}
{k.name} {k.user} {k.created ? formatDate(k.created) : "—"} {k.last_used ? formatDate(k.last_used) : __("Never", "yatra")}
)}

{__("Embed trips on other websites", "yatra")}

{(embedOn ?? !!snippet.enabled) && ( <>
{(embedTripsQuery.data || []).map((t: any) => ( ))}
setEmbedLimit(e.target.value)} />