add otp flow to resource auth portal

This commit is contained in:
Milo Schwartz
2024-12-15 17:47:07 -05:00
parent d3d2fe398b
commit 998fab6d0a
14 changed files with 1159 additions and 376 deletions

View File

@@ -10,7 +10,7 @@ import {
CardDescription,
CardFooter,
CardHeader,
CardTitle,
CardTitle
} from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
@@ -18,16 +18,26 @@ import { Input } from "@/components/ui/input";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
FormMessage
} from "@/components/ui/form";
import { LockIcon, Binary, Key, User } from "lucide-react";
import {
LockIcon,
Binary,
Key,
User,
Send,
ArrowLeft,
ArrowRight,
Lock
} from "lucide-react";
import {
InputOTP,
InputOTPGroup,
InputOTPSlot,
InputOTPSlot
} from "@app/components/ui/input-otp";
import { useRouter } from "next/navigation";
import { Alert, AlertDescription } from "@app/components/ui/alert";
@@ -39,18 +49,45 @@ 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: z
.string()
.length(6, { message: "PIN must be exactly 6 digits" })
.regex(/^\d+$/, { message: "PIN must only contain numbers" }),
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"
});
const passwordSchema = z.object({
password: z
.string()
.min(1, { message: "Password must be at least 1 character long" }),
password
});
const passwordRequestOtpSchema = z.object({
password,
email: z.string().email()
});
const passwordOtpSchema = z.object({
password,
email: z.string().email(),
otp: z.string()
});
type ResourceAuthPortalProps = {
@@ -68,6 +105,7 @@ type ResourceAuthPortalProps = {
export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
const router = useRouter();
const { toast } = useToast();
const getNumMethods = () => {
let colLength = 0;
@@ -84,6 +122,10 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
const [accessDenied, setAccessDenied] = useState<boolean>(false);
const [loadingLogin, setLoadingLogin] = useState(false);
const [otpState, setOtpState] = useState<
"idle" | "otp_requested" | "otp_sent"
>("idle");
const api = createApiClient(useEnvContext());
function getDefaultSelectedMethod() {
@@ -104,25 +146,77 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
const pinForm = useForm<z.infer<typeof pinSchema>>({
resolver: zodResolver(pinSchema),
defaultValues: {
pin: ""
}
});
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: {
password: "",
},
password: ""
}
});
const onPinSubmit = (values: z.infer<typeof pinSchema>) => {
const passwordRequestOtpForm = useForm<
z.infer<typeof passwordRequestOtpSchema>
>({
resolver: zodResolver(passwordRequestOtpSchema),
defaultValues: {
password: "",
email: ""
}
});
const passwordOtpForm = useForm<z.infer<typeof passwordOtpSchema>>({
resolver: zodResolver(passwordOtpSchema),
defaultValues: {
password: "",
email: "",
otp: ""
}
});
const onPinSubmit = (values: any) => {
setLoadingLogin(true);
api.post<AxiosResponse<AuthWithPasswordResponse>>(
`/auth/resource/${props.resource.id}/pincode`,
{ pincode: values.pin },
{ pincode: values.pin, 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);
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;
@@ -131,21 +225,59 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
.catch((e) => {
console.error(e);
setPincodeError(
formatAxiosError(e, "Failed to authenticate with pincode"),
formatAxiosError(e, "Failed to authenticate with pincode")
);
})
.then(() => setLoadingLogin(false));
};
const onPasswordSubmit = (values: z.infer<typeof passwordSchema>) => {
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) => {
setLoadingLogin(true);
api.post<AxiosResponse<AuthWithPasswordResponse>>(
`/auth/resource/${props.resource.id}/password`,
{
password: values.password,
},
email: values.email,
otp: values.otp
}
)
.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;
@@ -154,7 +286,7 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
.catch((e) => {
console.error(e);
setPasswordError(
formatAxiosError(e, "Failed to authenticate with password"),
formatAxiosError(e, "Failed to authenticate with password")
);
})
.finally(() => setLoadingLogin(false));
@@ -233,86 +365,237 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
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>
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>
{otpState === "idle" && (
<Form {...pinForm}>
<form
onSubmit={pinForm.handleSubmit(
onPinSubmit
)}
/>
{pincodeError && (
<Alert variant="destructive">
<AlertDescription>
{pincodeError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
className="space-y-4"
>
<LockIcon className="w-4 h-4 mr-2" />
Login with PIN
</Button>
</form>
</Form>
<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"
{...field}
/>
</FormControl>
<FormDescription>
A one-time
code will be
sent to this
email.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{pincodeError && (
<Alert variant="destructive">
<AlertDescription>
{pincodeError}
</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={() =>
resetPinForms()
}
>
Back to PIN
</Button>
</form>
</Form>
)}
{otpState === "otp_sent" && (
<Form {...pinOtpForm}>
<form
onSubmit={pinOtpForm.handleSubmit(
onPinSubmit
)}
className="space-y-4"
>
<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>
)}
</TabsContent>
)}
{props.methods.password && (
@@ -320,52 +603,202 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
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>
Password
</FormLabel>
<FormControl>
<Input
placeholder="Enter password"
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
{otpState === "idle" && (
<Form {...passwordForm}>
<form
onSubmit={passwordForm.handleSubmit(
onPasswordSubmit
)}
/>
{passwordError && (
<Alert variant="destructive">
<AlertDescription>
{passwordError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
className="space-y-4"
>
<LockIcon className="w-4 h-4 mr-2" />
Login with Password
</Button>
</form>
</Form>
<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>
)}
</TabsContent>
)}
{props.methods.sso && (