move all components to components dir

This commit is contained in:
miloschwartz
2025-09-04 11:18:42 -07:00
parent 4292d3262e
commit df85f13aea
90 changed files with 2166 additions and 86 deletions
@@ -1,160 +0,0 @@
"use client";
import { createApiClient } from "@app/lib/api";
import { Button } from "@app/components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle
} from "@app/components/ui/card";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { AuthWithAccessTokenResponse } from "@server/routers/resource";
import { AxiosResponse } from "axios";
import Link from "next/link";
import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
type AccessTokenProps = {
token: string;
resourceId?: number;
};
export default function AccessToken({
token,
resourceId
}: AccessTokenProps) {
const [loading, setLoading] = useState(true);
const [isValid, setIsValid] = useState(false);
const { env } = useEnvContext();
const api = createApiClient({ env });
const t = useTranslations();
function appendRequestToken(url: string, token: string) {
const fullUrl = new URL(url);
fullUrl.searchParams.append(
env.server.resourceSessionRequestParam,
token
);
return fullUrl.toString();
}
useEffect(() => {
if (!token) {
setLoading(false);
return;
}
let accessTokenId = "";
let accessToken = "";
const parts = token.split(".");
if (parts.length === 2) {
accessTokenId = parts[0];
accessToken = parts[1];
} else if (parts.length === 1) {
accessToken = parts[0];
} else {
setLoading(false);
return;
}
async function checkSHA256() {
try {
const res = await api.post<
AxiosResponse<AuthWithAccessTokenResponse>
>(`/auth/access-token`, {
accessToken,
accessTokenId
});
if (res.data.data.session) {
setIsValid(true);
window.location.href = appendRequestToken(
res.data.data.redirectUrl!,
res.data.data.session
);
}
} catch (e) {
console.error(t('accessTokenError'), e);
} finally {
setLoading(false);
}
}
async function check() {
try {
const res = await api.post<
AxiosResponse<AuthWithAccessTokenResponse>
>(`/auth/resource/${resourceId}/access-token`, {
accessToken,
accessTokenId
});
if (res.data.data.session) {
setIsValid(true);
window.location.href = appendRequestToken(
res.data.data.redirectUrl!,
res.data.data.session
);
}
} catch (e) {
console.error(t('accessTokenError'), e);
} finally {
setLoading(false);
}
}
if (!accessTokenId) {
// no access token id so check the sha256
checkSHA256();
} else {
check();
}
}, [token]);
function renderTitle() {
if (isValid) {
return t('accessGranted');
} else {
return t('accessUrlInvalid');
}
}
function renderContent() {
if (isValid) {
return (
<div>
{t('accessGrantedDescription')}
</div>
);
} else {
return (
<div>
{t('accessUrlInvalidDescription')}
<div className="text-center mt-4">
<Button>
<Link href="/">{t('goHome')}</Link>
</Button>
</div>
</div>
);
}
}
return loading ? (
<div></div>
) : (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle className="text-center text-2xl font-bold">
{renderTitle()}
</CardTitle>
</CardHeader>
<CardContent>{renderContent()}</CardContent>
</Card>
);
}
@@ -1,100 +0,0 @@
"use client";
import { useEffect, useState } from "react";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { createApiClient, formatAxiosError } from "@app/lib/api";
import { GenerateOidcUrlResponse } from "@server/routers/idp";
import { AxiosResponse } from "axios";
import { useRouter } from "next/navigation";
import {
Card,
CardHeader,
CardTitle,
CardContent,
CardDescription
} from "@app/components/ui/card";
import { Alert, AlertDescription } from "@app/components/ui/alert";
import { Loader2, CheckCircle2, AlertCircle } from "lucide-react";
import { useTranslations } from "next-intl";
type AutoLoginHandlerProps = {
resourceId: number;
skipToIdpId: number;
redirectUrl: string;
};
export default function AutoLoginHandler({
resourceId,
skipToIdpId,
redirectUrl
}: AutoLoginHandlerProps) {
const { env } = useEnvContext();
const api = createApiClient({ env });
const router = useRouter();
const t = useTranslations();
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function initiateAutoLogin() {
setLoading(true);
try {
const res = await api.post<
AxiosResponse<GenerateOidcUrlResponse>
>(`/auth/idp/${skipToIdpId}/oidc/generate-url`, {
redirectUrl
});
if (res.data.data.redirectUrl) {
// Redirect to the IDP for authentication
window.location.href = res.data.data.redirectUrl;
} else {
setError(t("autoLoginErrorNoRedirectUrl"));
}
} catch (e) {
console.error("Failed to generate OIDC URL:", e);
setError(formatAxiosError(e, t("autoLoginErrorGeneratingUrl")));
} finally {
setLoading(false);
}
}
initiateAutoLogin();
}, []);
return (
<div className="flex items-center justify-center min-h-screen">
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle>{t("autoLoginTitle")}</CardTitle>
<CardDescription>{t("autoLoginDescription")}</CardDescription>
</CardHeader>
<CardContent className="flex flex-col items-center space-y-4">
{loading && (
<div className="flex items-center space-x-2">
<Loader2 className="h-5 w-5 animate-spin" />
<span>{t("autoLoginProcessing")}</span>
</div>
)}
{!loading && !error && (
<div className="flex items-center space-x-2 text-green-600">
<CheckCircle2 className="h-5 w-5" />
<span>{t("autoLoginRedirecting")}</span>
</div>
)}
{error && (
<Alert variant="destructive" className="w-full">
<AlertCircle className="h-5 w-5" />
<AlertDescription className="flex flex-col space-y-2">
<span>{t("autoLoginError")}</span>
<span className="text-xs">{error}</span>
</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
</div>
);
}
@@ -1,34 +0,0 @@
"use client";
import { Button } from "@app/components/ui/button";
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
} from "@app/components/ui/card";
import Link from "next/link";
import { useTranslations } from "next-intl";
export default function ResourceAccessDenied() {
const t = useTranslations();
return (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle className="text-center text-2xl font-bold">
{t('accessDenied')}
</CardTitle>
</CardHeader>
<CardContent>
{t('accessDeniedDescription')}
<div className="text-center mt-4">
<Button>
<Link href="/">{t('goHome')}</Link>
</Button>
</div>
</CardContent>
</Card>
);
}
@@ -1,662 +0,0 @@
"use client";
import { useState } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle
} from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage
} from "@/components/ui/form";
import { LockIcon, Binary, Key, User, Send, AtSign } from "lucide-react";
import {
InputOTP,
InputOTPGroup,
InputOTPSlot
} from "@app/components/ui/input-otp";
import { useRouter } from "next/navigation";
import { Alert, AlertDescription } from "@app/components/ui/alert";
import { formatAxiosError } from "@app/lib/api";
import { AxiosResponse } from "axios";
import LoginForm, { LoginFormIDP } from "@app/components/LoginForm";
import {
AuthWithPasswordResponse,
AuthWithWhitelistResponse
} from "@server/routers/resource";
import ResourceAccessDenied from "./ResourceAccessDenied";
import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { toast } from "@app/hooks/useToast";
import Link from "next/link";
import Image from "next/image";
import { useSupporterStatusContext } from "@app/hooks/useSupporterStatusContext";
import { useTranslations } from "next-intl";
const pinSchema = z.object({
pin: z
.string()
.length(6, { message: "PIN must be exactly 6 digits" })
.regex(/^\d+$/, { message: "PIN must only contain numbers" })
});
const passwordSchema = z.object({
password: z.string().min(1, {
message: "Password must be at least 1 character long"
})
});
const requestOtpSchema = z.object({
email: z.string().email()
});
const submitOtpSchema = z.object({
email: z.string().email(),
otp: z.string().min(1, {
message: "OTP must be at least 1 character long"
})
});
type ResourceAuthPortalProps = {
methods: {
password: boolean;
pincode: boolean;
sso: boolean;
whitelist: boolean;
};
resource: {
name: string;
id: number;
};
redirect: string;
idps?: LoginFormIDP[];
};
export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
const router = useRouter();
const t = useTranslations();
const getNumMethods = () => {
let colLength = 0;
if (props.methods.pincode) colLength++;
if (props.methods.password) colLength++;
if (props.methods.sso) colLength++;
if (props.methods.whitelist) colLength++;
return colLength;
};
const [numMethods, setNumMethods] = useState(getNumMethods());
const [passwordError, setPasswordError] = useState<string | null>(null);
const [pincodeError, setPincodeError] = useState<string | null>(null);
const [whitelistError, setWhitelistError] = useState<string | null>(null);
const [accessDenied, setAccessDenied] = useState<boolean>(false);
const [loadingLogin, setLoadingLogin] = useState(false);
const [otpState, setOtpState] = useState<"idle" | "otp_sent">("idle");
const { env } = useEnvContext();
const api = createApiClient({ env });
const { supporterStatus } = useSupporterStatusContext();
function getDefaultSelectedMethod() {
if (props.methods.sso) {
return "sso";
}
if (props.methods.password) {
return "password";
}
if (props.methods.pincode) {
return "pin";
}
if (props.methods.whitelist) {
return "whitelist";
}
}
const [activeTab, setActiveTab] = useState(getDefaultSelectedMethod());
const pinForm = useForm<z.infer<typeof pinSchema>>({
resolver: zodResolver(pinSchema),
defaultValues: {
pin: ""
}
});
const passwordForm = useForm<z.infer<typeof passwordSchema>>({
resolver: zodResolver(passwordSchema),
defaultValues: {
password: ""
}
});
const requestOtpForm = useForm<z.infer<typeof requestOtpSchema>>({
resolver: zodResolver(requestOtpSchema),
defaultValues: {
email: ""
}
});
const submitOtpForm = useForm<z.infer<typeof submitOtpSchema>>({
resolver: zodResolver(submitOtpSchema),
defaultValues: {
email: "",
otp: ""
}
});
function appendRequestToken(url: string, token: string) {
const fullUrl = new URL(url);
fullUrl.searchParams.append(
env.server.resourceSessionRequestParam,
token
);
return fullUrl.toString();
}
const onWhitelistSubmit = (values: any) => {
setLoadingLogin(true);
api.post<AxiosResponse<AuthWithWhitelistResponse>>(
`/auth/resource/${props.resource.id}/whitelist`,
{ email: values.email, otp: values.otp }
)
.then((res) => {
setWhitelistError(null);
if (res.data.data.otpSent) {
setOtpState("otp_sent");
submitOtpForm.setValue("email", values.email);
toast({
title: t("otpEmailSent"),
description: t("otpEmailSentDescription")
});
return;
}
const session = res.data.data.session;
if (session) {
window.location.href = appendRequestToken(
props.redirect,
session
);
}
})
.catch((e) => {
console.error(e);
setWhitelistError(
formatAxiosError(e, t("otpEmailErrorAuthenticate"))
);
})
.then(() => setLoadingLogin(false));
};
const onPinSubmit = (values: z.infer<typeof pinSchema>) => {
setLoadingLogin(true);
api.post<AxiosResponse<AuthWithPasswordResponse>>(
`/auth/resource/${props.resource.id}/pincode`,
{ pincode: values.pin }
)
.then((res) => {
setPincodeError(null);
const session = res.data.data.session;
if (session) {
window.location.href = appendRequestToken(
props.redirect,
session
);
}
})
.catch((e) => {
console.error(e);
setPincodeError(
formatAxiosError(e, t("pincodeErrorAuthenticate"))
);
})
.then(() => setLoadingLogin(false));
};
const onPasswordSubmit = (values: z.infer<typeof passwordSchema>) => {
setLoadingLogin(true);
api.post<AxiosResponse<AuthWithPasswordResponse>>(
`/auth/resource/${props.resource.id}/password`,
{
password: values.password
}
)
.then((res) => {
setPasswordError(null);
const session = res.data.data.session;
if (session) {
window.location.href = appendRequestToken(
props.redirect,
session
);
}
})
.catch((e) => {
console.error(e);
setPasswordError(
formatAxiosError(e, t("passwordErrorAuthenticate"))
);
})
.finally(() => setLoadingLogin(false));
};
async function handleSSOAuth() {
let isAllowed = false;
try {
await api.get(`/resource/${props.resource.id}`);
isAllowed = true;
} catch (e) {
setAccessDenied(true);
}
if (isAllowed) {
// window.location.href = props.redirect;
router.refresh();
}
}
function getTitle() {
return t("authenticationRequired");
}
function getSubtitle(resourceName: string) {
return numMethods > 1
? t("authenticationMethodChoose", { name: props.resource.name })
: t("authenticationRequest", { name: props.resource.name });
}
return (
<div>
{!accessDenied ? (
<div>
<div className="text-center mb-2">
<span className="text-sm text-muted-foreground">
{t("poweredBy")}{" "}
<Link
href="https://github.com/fosrl/pangolin"
target="_blank"
rel="noopener noreferrer"
className="underline"
>
Pangolin
</Link>
</span>
</div>
<Card>
<CardHeader>
<CardTitle>{getTitle()}</CardTitle>
<CardDescription>
{getSubtitle(props.resource.name)}
</CardDescription>
</CardHeader>
<CardContent>
<Tabs
value={activeTab}
onValueChange={setActiveTab}
orientation="horizontal"
>
{numMethods > 1 && (
<TabsList
className={`grid w-full ${
numMethods === 1
? "grid-cols-1"
: numMethods === 2
? "grid-cols-2"
: numMethods === 3
? "grid-cols-3"
: "grid-cols-4"
}`}
>
{props.methods.pincode && (
<TabsTrigger value="pin">
<Binary className="w-4 h-4 mr-1" />{" "}
PIN
</TabsTrigger>
)}
{props.methods.password && (
<TabsTrigger value="password">
<Key className="w-4 h-4 mr-1" />{" "}
{t("password")}
</TabsTrigger>
)}
{props.methods.sso && (
<TabsTrigger value="sso">
<User className="w-4 h-4 mr-1" />{" "}
{t("user")}
</TabsTrigger>
)}
{props.methods.whitelist && (
<TabsTrigger value="whitelist">
<AtSign className="w-4 h-4 mr-1" />{" "}
{t("email")}
</TabsTrigger>
)}
</TabsList>
)}
{props.methods.pincode && (
<TabsContent
value="pin"
className={`${numMethods <= 1 ? "mt-0" : ""}`}
>
<Form {...pinForm}>
<form
onSubmit={pinForm.handleSubmit(
onPinSubmit
)}
className="space-y-4"
>
<FormField
control={pinForm.control}
name="pin"
render={({ field }) => (
<FormItem>
<FormLabel>
{t(
"pincodeInput"
)}
</FormLabel>
<FormControl>
<div className="flex justify-center">
<InputOTP
maxLength={
6
}
{...field}
>
<InputOTPGroup className="flex">
<InputOTPSlot
index={
0
}
obscured
/>
<InputOTPSlot
index={
1
}
obscured
/>
<InputOTPSlot
index={
2
}
obscured
/>
<InputOTPSlot
index={
3
}
obscured
/>
<InputOTPSlot
index={
4
}
obscured
/>
<InputOTPSlot
index={
5
}
obscured
/>
</InputOTPGroup>
</InputOTP>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{pincodeError && (
<Alert variant="destructive">
<AlertDescription>
{pincodeError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<LockIcon className="w-4 h-4 mr-2" />
{t("pincodeSubmit")}
</Button>
</form>
</Form>
</TabsContent>
)}
{props.methods.password && (
<TabsContent
value="password"
className={`${numMethods <= 1 ? "mt-0" : ""}`}
>
<Form {...passwordForm}>
<form
onSubmit={passwordForm.handleSubmit(
onPasswordSubmit
)}
className="space-y-4"
>
<FormField
control={
passwordForm.control
}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("password")}
</FormLabel>
<FormControl>
<Input
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{passwordError && (
<Alert variant="destructive">
<AlertDescription>
{passwordError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<LockIcon className="w-4 h-4 mr-2" />
{t("passwordSubmit")}
</Button>
</form>
</Form>
</TabsContent>
)}
{props.methods.sso && (
<TabsContent
value="sso"
className={`${numMethods <= 1 ? "mt-0" : ""}`}
>
<LoginForm
idps={props.idps}
redirect={props.redirect}
onLogin={async () =>
await handleSSOAuth()
}
/>
</TabsContent>
)}
{props.methods.whitelist && (
<TabsContent
value="whitelist"
className={`${numMethods <= 1 ? "mt-0" : ""}`}
>
{otpState === "idle" && (
<Form {...requestOtpForm}>
<form
onSubmit={requestOtpForm.handleSubmit(
onWhitelistSubmit
)}
className="space-y-4"
>
<FormField
control={
requestOtpForm.control
}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("email")}
</FormLabel>
<FormControl>
<Input
type="email"
{...field}
/>
</FormControl>
<FormDescription>
{t(
"otpEmailDescription"
)}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{whitelistError && (
<Alert variant="destructive">
<AlertDescription>
{whitelistError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<Send className="w-4 h-4 mr-2" />
{t("otpEmailSend")}
</Button>
</form>
</Form>
)}
{otpState === "otp_sent" && (
<Form {...submitOtpForm}>
<form
onSubmit={submitOtpForm.handleSubmit(
onWhitelistSubmit
)}
className="space-y-4"
>
<FormField
control={
submitOtpForm.control
}
name="otp"
render={({ field }) => (
<FormItem>
<FormLabel>
{t(
"otpEmail"
)}
</FormLabel>
<FormControl>
<Input
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{whitelistError && (
<Alert variant="destructive">
<AlertDescription>
{whitelistError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<LockIcon className="w-4 h-4 mr-2" />
{t("otpEmailSubmit")}
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() => {
setOtpState("idle");
submitOtpForm.reset();
}}
>
{t("backToEmail")}
</Button>
</form>
</Form>
)}
</TabsContent>
)}
</Tabs>
</CardContent>
</Card>
{supporterStatus?.visible && (
<div className="text-center mt-2">
<span className="text-sm text-muted-foreground opacity-50">
{t("noSupportKey")}
</span>
</div>
)}
</div>
) : (
<ResourceAccessDenied />
)}
</div>
);
}
@@ -1,33 +0,0 @@
import { Button } from "@app/components/ui/button";
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
} from "@app/components/ui/card";
import Link from "next/link";
import { getTranslations } from "next-intl/server";
export default async function ResourceNotFound() {
const t = await getTranslations();
return (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle className="text-center text-2xl font-bold">
{t('resourceNotFound')}
</CardTitle>
</CardHeader>
<CardContent>
{t('resourceNotFoundDescription')}
<div className="text-center mt-4">
<Button>
<Link href="/">{t('goHome')}</Link>
</Button>
</div>
</CardContent>
</Card>
);
}
+5 -5
View File
@@ -2,20 +2,20 @@ import {
GetResourceAuthInfoResponse,
GetExchangeTokenResponse
} from "@server/routers/resource";
import ResourceAuthPortal from "./ResourceAuthPortal";
import ResourceAuthPortal from "@app/components/ResourceAuthPortal";
import { internal, priv } from "@app/lib/api";
import { AxiosResponse } from "axios";
import { authCookieHeader } from "@app/lib/api/cookies";
import { cache } from "react";
import { verifySession } from "@app/lib/auth/verifySession";
import { redirect } from "next/navigation";
import ResourceNotFound from "./ResourceNotFound";
import ResourceAccessDenied from "./ResourceAccessDenied";
import AccessToken from "./AccessToken";
import ResourceNotFound from "@app/components/ResourceNotFound";
import ResourceAccessDenied from "@app/components/ResourceAccessDenied";
import AccessToken from "@app/components/AccessToken";
import { pullEnv } from "@app/lib/pullEnv";
import { LoginFormIDP } from "@app/components/LoginForm";
import { ListIdpsResponse } from "@server/routers/idp";
import AutoLoginHandler from "./AutoLoginHandler";
import AutoLoginHandler from "@app/components/AutoLoginHandler";
export const dynamic = "force-dynamic";