add resource whitelist auth method

This commit is contained in:
Milo Schwartz
2024-12-16 22:40:42 -05:00
parent 998fab6d0a
commit 207a7b8a39
20 changed files with 970 additions and 739 deletions

View File

@@ -32,7 +32,8 @@ import {
Send,
ArrowLeft,
ArrowRight,
Lock
Lock,
AtSign
} from "lucide-react";
import {
InputOTP,
@@ -44,50 +45,35 @@ import { Alert, AlertDescription } from "@app/components/ui/alert";
import { formatAxiosError } from "@app/lib/utils";
import { AxiosResponse } from "axios";
import LoginForm from "@app/components/LoginForm";
import { AuthWithPasswordResponse } from "@server/routers/resource";
import { AuthWithPasswordResponse, AuthWithWhitelistResponse } from "@server/routers/resource";
import { redirect } from "next/dist/server/api-utils";
import ResourceAccessDenied from "./ResourceAccessDenied";
import { createApiClient } from "@app/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { useToast } from "@app/hooks/useToast";
const pin = z
.string()
.length(6, { message: "PIN must be exactly 6 digits" })
.regex(/^\d+$/, { message: "PIN must only contain numbers" });
const pinSchema = z.object({
pin
});
const pinRequestOtpSchema = z.object({
pin,
email: z.string().email()
});
const pinOtpSchema = z.object({
pin,
email: z.string().email(),
otp: z.string()
});
const password = z.string().min(1, {
message: "Password must be at least 1 character long"
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
password: z.string().min(1, {
message: "Password must be at least 1 character long"
})
});
const passwordRequestOtpSchema = z.object({
password,
const requestOtpSchema = z.object({
email: z.string().email()
});
const passwordOtpSchema = z.object({
password,
const submitOtpSchema = z.object({
email: z.string().email(),
otp: z.string()
otp: z.string().min(1, {
message: "OTP must be at least 1 character long"
})
});
type ResourceAuthPortalProps = {
@@ -95,6 +81,7 @@ type ResourceAuthPortalProps = {
password: boolean;
pincode: boolean;
sso: boolean;
whitelist: boolean;
};
resource: {
name: string;
@@ -112,6 +99,7 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
if (props.methods.pincode) colLength++;
if (props.methods.password) colLength++;
if (props.methods.sso) colLength++;
if (props.methods.whitelist) colLength++;
return colLength;
};
@@ -119,12 +107,11 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
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_requested" | "otp_sent"
>("idle");
const [otpState, setOtpState] = useState<"idle" | "otp_sent">("idle");
const api = createApiClient(useEnvContext());
@@ -140,6 +127,10 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
if (props.methods.pincode) {
return "pin";
}
if (props.methods.whitelist) {
return "whitelist";
}
}
const [activeTab, setActiveTab] = useState(getDefaultSelectedMethod());
@@ -151,23 +142,6 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
}
});
const pinRequestOtpForm = useForm<z.infer<typeof pinRequestOtpSchema>>({
resolver: zodResolver(pinRequestOtpSchema),
defaultValues: {
pin: "",
email: ""
}
});
const pinOtpForm = useForm<z.infer<typeof pinOtpSchema>>({
resolver: zodResolver(pinOtpSchema),
defaultValues: {
pin: "",
email: "",
otp: ""
}
});
const passwordForm = useForm<z.infer<typeof passwordSchema>>({
resolver: zodResolver(passwordSchema),
defaultValues: {
@@ -175,45 +149,37 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
}
});
const passwordRequestOtpForm = useForm<
z.infer<typeof passwordRequestOtpSchema>
>({
resolver: zodResolver(passwordRequestOtpSchema),
const requestOtpForm = useForm<z.infer<typeof requestOtpSchema>>({
resolver: zodResolver(requestOtpSchema),
defaultValues: {
password: "",
email: ""
}
});
const passwordOtpForm = useForm<z.infer<typeof passwordOtpSchema>>({
resolver: zodResolver(passwordOtpSchema),
const submitOtpForm = useForm<z.infer<typeof submitOtpSchema>>({
resolver: zodResolver(submitOtpSchema),
defaultValues: {
password: "",
email: "",
otp: ""
}
});
const onPinSubmit = (values: any) => {
const onWhitelistSubmit = (values: any) => {
setLoadingLogin(true);
api.post<AxiosResponse<AuthWithPasswordResponse>>(
`/auth/resource/${props.resource.id}/pincode`,
{ pincode: values.pin, email: values.email, otp: values.otp }
api.post<AxiosResponse<AuthWithWhitelistResponse>>(
`/auth/resource/${props.resource.id}/whitelist`,
{ email: values.email, otp: values.otp }
)
.then((res) => {
setPincodeError(null);
if (res.data.data.otpRequested) {
setOtpState("otp_requested");
pinRequestOtpForm.setValue("pin", values.pin);
return;
} else if (res.data.data.otpSent) {
pinOtpForm.setValue("email", values.email);
pinOtpForm.setValue("pin", values.pin);
setWhitelistError(null);
if (res.data.data.otpSent) {
setOtpState("otp_sent");
submitOtpForm.setValue("email", values.email);
toast({
title: "OTP Sent",
description: `OTP sent to ${values.email}`
description: "An OTP has been sent to your email"
});
setOtpState("otp_sent");
return;
}
@@ -222,6 +188,28 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
window.location.href = props.redirect;
}
})
.catch((e) => {
console.error(e);
setWhitelistError(
formatAxiosError(e, "Failed to authenticate with email")
);
})
.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 = props.redirect;
}
})
.catch((e) => {
console.error(e);
setPincodeError(
@@ -231,53 +219,17 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
.then(() => setLoadingLogin(false));
};
const resetPasswordForms = () => {
passwordForm.reset();
passwordRequestOtpForm.reset();
passwordOtpForm.reset();
setOtpState("idle");
setPasswordError(null);
};
const resetPinForms = () => {
pinForm.reset();
pinRequestOtpForm.reset();
pinOtpForm.reset();
setOtpState("idle");
setPincodeError(null);
}
const onPasswordSubmit = (values: any) => {
const onPasswordSubmit = (values: z.infer<typeof passwordSchema>) => {
setLoadingLogin(true);
api.post<AxiosResponse<AuthWithPasswordResponse>>(
`/auth/resource/${props.resource.id}/password`,
{
password: values.password,
email: values.email,
otp: values.otp
password: values.password
}
)
.then((res) => {
setPasswordError(null);
if (res.data.data.otpRequested) {
setOtpState("otp_requested");
passwordRequestOtpForm.setValue(
"password",
values.password
);
return;
} else if (res.data.data.otpSent) {
passwordOtpForm.setValue("email", values.email);
passwordOtpForm.setValue("password", values.password);
toast({
title: "OTP Sent",
description: `OTP sent to ${values.email}`
});
setOtpState("otp_sent");
return;
}
const session = res.data.data.session;
if (session) {
window.location.href = props.redirect;
@@ -337,7 +289,9 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
? "grid-cols-1"
: numMethods === 2
? "grid-cols-2"
: "grid-cols-3"
: numMethods === 3
? "grid-cols-3"
: "grid-cols-4"
}`}
>
{props.methods.pincode && (
@@ -358,6 +312,12 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
User
</TabsTrigger>
)}
{props.methods.whitelist && (
<TabsTrigger value="whitelist">
<AtSign className="w-4 h-4 mr-1" />{" "}
Email
</TabsTrigger>
)}
</TabsList>
)}
{props.methods.pincode && (
@@ -365,237 +325,86 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
value="pin"
className={`${numMethods <= 1 ? "mt-0" : ""}`}
>
{otpState === "idle" && (
<Form {...pinForm}>
<form
onSubmit={pinForm.handleSubmit(
onPinSubmit
)}
className="space-y-4"
>
<FormField
control={
pinForm.control
}
name="pin"
render={({ field }) => (
<FormItem>
<FormLabel>
6-digit PIN
Code
</FormLabel>
<FormControl>
<div className="flex justify-center">
<InputOTP
maxLength={
6
}
{...field}
>
<InputOTPGroup className="flex">
<InputOTPSlot
index={
0
}
/>
<InputOTPSlot
index={
1
}
/>
<InputOTPSlot
index={
2
}
/>
<InputOTPSlot
index={
3
}
/>
<InputOTPSlot
index={
4
}
/>
<InputOTPSlot
index={
5
}
/>
</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" />
Login with PIN
</Button>
</form>
</Form>
)}
{otpState === "otp_requested" && (
<Form {...pinRequestOtpForm}>
<form
onSubmit={pinRequestOtpForm.handleSubmit(
onPinSubmit
)}
className="space-y-4"
>
<FormField
control={
pinRequestOtpForm.control
}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>
Email
</FormLabel>
<FormControl>
<Input
placeholder="Enter email"
type="email"
<Form {...pinForm}>
<form
onSubmit={pinForm.handleSubmit(
onPinSubmit
)}
className="space-y-4"
>
<FormField
control={pinForm.control}
name="pin"
render={({ field }) => (
<FormItem>
<FormLabel>
6-digit PIN Code
</FormLabel>
<FormControl>
<div className="flex justify-center">
<InputOTP
maxLength={
6
}
{...field}
/>
</FormControl>
<FormDescription>
A one-time
code will be
sent to this
email.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{pincodeError && (
<Alert variant="destructive">
<AlertDescription>
{pincodeError}
</AlertDescription>
</Alert>
>
<InputOTPGroup className="flex">
<InputOTPSlot
index={
0
}
/>
<InputOTPSlot
index={
1
}
/>
<InputOTPSlot
index={
2
}
/>
<InputOTPSlot
index={
3
}
/>
<InputOTPSlot
index={
4
}
/>
<InputOTPSlot
index={
5
}
/>
</InputOTPGroup>
</InputOTP>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<Send className="w-4 h-4 mr-2" />
Send OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() =>
resetPinForms()
}
>
Back to PIN
</Button>
</form>
</Form>
)}
{otpState === "otp_sent" && (
<Form {...pinOtpForm}>
<form
onSubmit={pinOtpForm.handleSubmit(
onPinSubmit
)}
className="space-y-4"
/>
{pincodeError && (
<Alert variant="destructive">
<AlertDescription>
{pincodeError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<FormField
control={
pinOtpForm.control
}
name="otp"
render={({ field }) => (
<FormItem>
<FormLabel>
One-Time
Password
(OTP)
</FormLabel>
<FormControl>
<Input
placeholder="Enter OTP"
type="otp"
{...field}
/>
</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" />
Submit OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() => {
setOtpState(
"otp_requested"
);
pinOtpForm.reset();
}}
>
Resend OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() =>
resetPinForms()
}
>
Back to PIN
</Button>
</form>
</Form>
)}
<LockIcon className="w-4 h-4 mr-2" />
Login with PIN
</Button>
</form>
</Form>
</TabsContent>
)}
{props.methods.password && (
@@ -603,202 +412,54 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
value="password"
className={`${numMethods <= 1 ? "mt-0" : ""}`}
>
{otpState === "idle" && (
<Form {...passwordForm}>
<form
onSubmit={passwordForm.handleSubmit(
onPasswordSubmit
<Form {...passwordForm}>
<form
onSubmit={passwordForm.handleSubmit(
onPasswordSubmit
)}
className="space-y-4"
>
<FormField
control={
passwordForm.control
}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>
Password
</FormLabel>
<FormControl>
<Input
placeholder="Enter password"
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
className="space-y-4"
/>
{passwordError && (
<Alert variant="destructive">
<AlertDescription>
{passwordError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<FormField
control={
passwordForm.control
}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>
Password
</FormLabel>
<FormControl>
<Input
placeholder="Enter password"
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" />
Login with Password
</Button>
</form>
</Form>
)}
{otpState === "otp_requested" && (
<Form {...passwordRequestOtpForm}>
<form
onSubmit={passwordRequestOtpForm.handleSubmit(
onPasswordSubmit
)}
className="space-y-4"
>
<FormField
control={
passwordRequestOtpForm.control
}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>
Email
</FormLabel>
<FormControl>
<Input
placeholder="Enter email"
type="email"
{...field}
/>
</FormControl>
<FormDescription>
A one-time
code will be
sent to this
email.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{passwordError && (
<Alert variant="destructive">
<AlertDescription>
{passwordError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<Send className="w-4 h-4 mr-2" />
Send OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() =>
resetPasswordForms()
}
>
Back to Password
</Button>
</form>
</Form>
)}
{otpState === "otp_sent" && (
<Form {...passwordOtpForm}>
<form
onSubmit={passwordOtpForm.handleSubmit(
onPasswordSubmit
)}
className="space-y-4"
>
<FormField
control={
passwordOtpForm.control
}
name="otp"
render={({ field }) => (
<FormItem>
<FormLabel>
One-Time
Password
(OTP)
</FormLabel>
<FormControl>
<Input
placeholder="Enter OTP"
type="otp"
{...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" />
Submit OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() => {
setOtpState(
"otp_requested"
);
passwordOtpForm.reset();
}}
>
Resend OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() =>
resetPasswordForms()
}
>
Back to Password
</Button>
</form>
</Form>
)}
<LockIcon className="w-4 h-4 mr-2" />
Login with Password
</Button>
</form>
</Form>
</TabsContent>
)}
{props.methods.sso && (
@@ -818,6 +479,134 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
/>
</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>
Email
</FormLabel>
<FormControl>
<Input
placeholder="Enter email"
type="email"
{...field}
/>
</FormControl>
<FormDescription>
A one-time
code will be
sent to this
email.
</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" />
Send One-time Code
</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>
One-Time
Password
(OTP)
</FormLabel>
<FormControl>
<Input
placeholder="Enter OTP"
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" />
Submit OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() => {
setOtpState("idle");
submitOtpForm.reset();
}}
>
Back to Email
</Button>
</form>
</Form>
)}
</TabsContent>
)}
</Tabs>
</CardContent>
</Card>

View File

@@ -120,6 +120,7 @@ export default async function ResourceAuthPage(props: {
password: authInfo.password,
pincode: authInfo.pincode,
sso: authInfo.sso && !userIsUnauthorized,
whitelist: authInfo.whitelist
}}
resource={{
name: authInfo.resourceName,

View File

@@ -23,11 +23,12 @@ import {
} from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { SignUpResponse } from "@server/routers/auth";
import { api } from "@app/api";
import { useRouter } from "next/navigation";
import { passwordSchema } from "@server/auth/passwordSchema";
import { AxiosResponse } from "axios";
import { formatAxiosError } from "@app/lib/utils";
import { createApiClient } from "@app/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
type SignupFormProps = {
redirect?: string;
@@ -47,6 +48,8 @@ const formSchema = z
export default function SignupForm({ redirect }: SignupFormProps) {
const router = useRouter();
const api = createApiClient(useEnvContext());
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);