peppa/apps/web/app/oauth/authorize/page.tsx

87 lines
3.7 KiB
TypeScript

import { checkAuthorizeRequest, OAuthError, type OAuthClient } from "@peppa/core";
import { redirect } from "next/navigation";
import { currentUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { approve, deny } from "./actions";
import { Brand } from "@/components/Brand";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { getT } from "@/lib/i18n";
import { pageTitle } from "@/lib/title";
export const dynamic = "force-dynamic";
type Params = Record<string, string | undefined>;
// PEP-274: the browser tab says which page it is.
export async function generateMetadata() {
const t = await getT();
return pageTitle(t, t("Доступ для приложения"));
}
export default async function Authorize({ searchParams }: { searchParams: Promise<Params> }) {
const p = await searchParams;
const user = await currentUser();
if (!user) redirect(`/login?next=${encodeURIComponent(`/oauth/authorize?${new URLSearchParams(p as Record<string, string>)}`)}`);
let client: OAuthClient | null = null;
let error: string | null = null;
try {
client = await checkAuthorizeRequest(db, {
clientId: p.client_id ?? "",
redirectUri: p.redirect_uri ?? "",
codeChallenge: p.code_challenge ?? "",
codeChallengeMethod: p.code_challenge_method ?? "",
responseType: p.response_type ?? "",
scope: p.scope,
});
} catch (e) {
error = e instanceof OAuthError ? e.message : (e as Error).message;
}
const t = await getT();
const host = p.redirect_uri ? new URL(p.redirect_uri).host : "";
return (
<main className="grid min-h-dvh place-items-center px-4">
<Card className="w-full max-w-md gap-4 p-6">
<Brand />
{error || !client ? (
<p role="alert" className="m-0 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm">{t("Запрос авторизации некорректен: {error}", { error: t.text(error ?? "") })}</p>
) : (
<>
<p className="m-0 text-sm">
<b>{client.name}</b> <span className="text-muted-foreground">({host})</span> {t("просит доступ к FORGE от имени")} <b>{user.login}</b>.
</p>
<ul className="m-0 flex list-disc flex-col gap-1 pl-5 text-sm">
<li>{t("видеть ваши проекты, эпики, задачи и вопросы агентов;")}</li>
<li>{t("создавать задачи и двигать карточки — перенос в «В работе» запускает агента;")}</li>
<li>{t("отвечать на вопросы агентов и принимать результат.")}</li>
</ul>
<p className="m-0 text-xs text-muted-foreground">{t("Отозвать доступ можно в «Настройки → Подключённые приложения».")}</p>
<div className="flex gap-2">
<form action={approve}>
<Hidden p={p} />
<Button variant="default">{t("Разрешить")}</Button>
</form>
<form action={deny}>
<Hidden p={p} />
<Button>{t("Отклонить")}</Button>
</form>
</div>
</>
)}
</Card>
</main>
);
}
function Hidden({ p }: { p: Params }) {
return (
<>
{(["client_id", "redirect_uri", "code_challenge", "code_challenge_method", "response_type", "scope", "state"] as const).map((k) => (
<input key={k} type="hidden" name={k} value={p[k] ?? ""} />
))}
</>
);
}
/** OAuth consent screen: who asks, what they get, allow / deny. */