added support for pin code auth

This commit is contained in:
Milo Schwartz
2024-11-23 20:08:56 -05:00
parent 78b23a8956
commit ad5ea3564b
14 changed files with 653 additions and 88 deletions

View File

@@ -1,23 +0,0 @@
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
} from "@app/components/ui/card";
export default async function ResourceAccessDenied() {
return (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle className="text-center text-2xl font-bold">
Access Denied
</CardTitle>
</CardHeader>
<CardContent>
You're not alowed to access this resource. If this is a mistake,
please contact the administrator.
</CardContent>
</Card>
);
}

View File

@@ -1,348 +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,
CardFooter,
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,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { LockIcon, UserIcon, Binary, Key, User } from "lucide-react";
import {
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from "@app/components/ui/input-otp";
import api from "@app/api";
import { useRouter } from "next/navigation";
import { Alert, AlertDescription } from "@app/components/ui/alert";
import { formatAxiosError } from "@app/lib/utils";
import { AxiosResponse } from "axios";
import { LoginResponse } from "@server/routers/auth";
import ResourceAccessDenied from "./ResourceAccessDenied";
import LoginForm from "@app/components/LoginForm";
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" }),
});
type ResourceAuthPortalProps = {
methods: {
password: boolean;
pincode: boolean;
sso: boolean;
};
resource: {
name: string;
id: number;
};
redirect: string;
};
export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
const router = useRouter();
const [passwordError, setPasswordError] = useState<string | null>(null);
const [accessDenied, setAccessDenied] = useState<boolean>(false);
function getDefaultSelectedMethod() {
if (props.methods.sso) {
return "sso";
}
if (props.methods.password) {
return "password";
}
if (props.methods.pincode) {
return "pin";
}
}
const [activeTab, setActiveTab] = useState(getDefaultSelectedMethod());
const getColLength = () => {
let colLength = 0;
if (props.methods.pincode) colLength++;
if (props.methods.password) colLength++;
if (props.methods.sso) colLength++;
return colLength;
};
const [numMethods, setNumMethods] = useState(getColLength());
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 onPinSubmit = (values: z.infer<typeof pinSchema>) => {
console.log("PIN authentication", values);
// Implement PIN authentication logic here
};
const onPasswordSubmit = (values: z.infer<typeof passwordSchema>) => {
api.post(`/resource/${props.resource.id}/auth/password`, {
password: values.password,
})
.then((res) => {
window.location.href = props.redirect;
})
.catch((e) => {
console.error(e);
setPasswordError(
formatAxiosError(e, "Failed to authenticate with password"),
);
});
};
async function handleSSOAuth() {
console.log("SSO authentication");
await api.get(`/resource/${props.resource.id}`).catch((e) => {
setAccessDenied(true);
});
if (!accessDenied) {
window.location.href = props.redirect;
}
}
return (
<div>
{!accessDenied ? (
<div>
<Card>
<CardHeader>
<CardTitle>Authentication Required</CardTitle>
<CardDescription>
{numMethods > 1
? `Choose your preferred method to access ${props.resource.name}`
: `You must authenticate to access ${props.resource.name}`}
</CardDescription>
</CardHeader>
<CardContent>
<Tabs
value={activeTab}
onValueChange={setActiveTab}
>
{numMethods > 1 && (
<TabsList
className={`grid w-full grid-cols-${numMethods}`}
>
{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" />{" "}
Password
</TabsTrigger>
)}
{props.methods.sso && (
<TabsTrigger value="sso">
<User className="w-4 h-4 mr-1" />{" "}
User
</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>
Enter 6-digit
PIN
</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>
)}
/>
<Button
type="submit"
className="w-full"
>
<LockIcon className="w-4 h-4 mr-2" />
Login with PIN
</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>
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"
>
<LockIcon className="w-4 h-4 mr-2" />
Login with Password
</Button>
</form>
</Form>
</TabsContent>
)}
{props.methods.sso && (
<TabsContent
value="sso"
className={`${numMethods <= 1 ? "mt-0" : ""}`}
>
<LoginForm
onLogin={async () =>
await handleSSOAuth()
}
/>
</TabsContent>
)}
</Tabs>
</CardContent>
</Card>
{/* {activeTab === "sso" && (
<div className="flex justify-center mt-4">
<p className="text-sm text-muted-foreground">
Don't have an account?{" "}
<a href="#" className="underline">
Sign up
</a>
</p>
</div>
)} */}
</div>
) : (
<ResourceAccessDenied />
)}
</div>
);
}

View File

@@ -1,22 +0,0 @@
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
} from "@app/components/ui/card";
export default async function ResourceNotFound() {
return (
<Card className="w-full max-w-md">
<CardHeader>
<CardTitle className="text-center text-2xl font-bold">
Resource Not Found
</CardTitle>
</CardHeader>
<CardContent>
The resource you're trying to access does not exist
</CardContent>
</Card>
);
}

View File

@@ -1,105 +0,0 @@
import {
GetResourceAuthInfoResponse,
GetResourceResponse,
} from "@server/routers/resource";
import ResourceAuthPortal from "./components/ResourceAuthPortal";
import { internal } from "@app/api";
import { AxiosResponse } from "axios";
import { authCookieHeader } from "@app/api/cookies";
import { cache } from "react";
import { verifySession } from "@app/lib/auth/verifySession";
import { redirect } from "next/navigation";
import ResourceNotFound from "./components/ResourceNotFound";
import ResourceAccessDenied from "./components/ResourceAccessDenied";
export default async function ResourceAuthPage(props: {
params: Promise<{ resourceId: number; orgId: string }>;
searchParams: Promise<{ r: string }>;
}) {
const params = await props.params;
const searchParams = await props.searchParams;
let authInfo: GetResourceAuthInfoResponse | undefined;
try {
const res = await internal.get<
AxiosResponse<GetResourceAuthInfoResponse>
>(`/resource/${params.resourceId}/auth`, await authCookieHeader());
if (res && res.status === 200) {
authInfo = res.data.data;
}
} catch (e) {
console.error(e);
console.log("resource not found");
}
const getUser = cache(verifySession);
const user = await getUser();
if (!authInfo) {
return (
<div className="w-full max-w-md mx-auto p-3 md:mt-32">
<ResourceNotFound />
</div>
);
}
const hasAuth = authInfo.password || authInfo.pincode || authInfo.sso;
const isSSOOnly = authInfo.sso && !authInfo.password && !authInfo.pincode;
if (!hasAuth) {
return (
<div className="w-full max-w-md mx-auto p-3 md:mt-32">
<ResourceAccessDenied />
</div>
);
}
let userIsUnauthorized = false;
if (user && authInfo.sso) {
let doRedirect = false;
try {
const res = await internal.get<AxiosResponse<GetResourceResponse>>(
`/resource/${params.resourceId}`,
await authCookieHeader(),
);
console.log(res.data);
doRedirect = true;
} catch (e) {
console.error(e);
userIsUnauthorized = true;
}
if (doRedirect) {
redirect(searchParams.r || authInfo.url);
}
}
if (userIsUnauthorized && isSSOOnly) {
return (
<div className="w-full max-w-md mx-auto p-3 md:mt-32">
<ResourceAccessDenied />
</div>
);
}
return (
<>
<div className="w-full max-w-md mx-auto p-3 md:mt-32">
<ResourceAuthPortal
methods={{
password: authInfo.password,
pincode: authInfo.pincode,
sso: authInfo.sso && !userIsUnauthorized,
}}
resource={{
name: authInfo.resourceName,
id: authInfo.resourceId,
}}
redirect={searchParams.r || authInfo.url}
/>
</div>
</>
);
}

View File

@@ -0,0 +1,199 @@
"use client";
import api from "@app/api";
import { Button } from "@app/components/ui/button";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@app/components/ui/form";
import { Input } from "@app/components/ui/input";
import { useToast } from "@app/hooks/useToast";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import {
Credenza,
CredenzaBody,
CredenzaClose,
CredenzaContent,
CredenzaDescription,
CredenzaFooter,
CredenzaHeader,
CredenzaTitle,
} from "@app/components/Credenza";
import { formatAxiosError } from "@app/lib/utils";
import { AxiosResponse } from "axios";
import { Resource } from "@server/db/schema";
import {
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from "@app/components/ui/input-otp";
const setPincodeFormSchema = z.object({
pincode: z.string().length(6),
});
type SetPincodeFormValues = z.infer<typeof setPincodeFormSchema>;
const defaultValues: Partial<SetPincodeFormValues> = {
pincode: "",
};
type SetPincodeFormProps = {
open: boolean;
setOpen: (open: boolean) => void;
resourceId: number;
onSetPincode?: () => void;
};
export default function SetResourcePincodeForm({
open,
setOpen,
resourceId,
onSetPincode,
}: SetPincodeFormProps) {
const { toast } = useToast();
const [loading, setLoading] = useState(false);
const form = useForm<SetPincodeFormValues>({
resolver: zodResolver(setPincodeFormSchema),
defaultValues,
});
useEffect(() => {
if (!open) {
return;
}
form.reset();
}, [open]);
async function onSubmit(data: SetPincodeFormValues) {
setLoading(true);
api.post<AxiosResponse<Resource>>(`/resource/${resourceId}/pincode`, {
pincode: data.pincode,
})
.catch((e) => {
toast({
variant: "destructive",
title: "Error setting resource PIN code",
description: formatAxiosError(
e,
"An error occurred while setting the resource PIN code",
),
});
})
.then(() => {
toast({
title: "Resource PIN code set",
description:
"The resource pincode has been set successfully",
});
if (onSetPincode) {
onSetPincode();
}
})
.finally(() => setLoading(false));
}
return (
<>
<Credenza
open={open}
onOpenChange={(val) => {
setOpen(val);
setLoading(false);
form.reset();
}}
>
<CredenzaContent>
<CredenzaHeader>
<CredenzaTitle>Set Pincode</CredenzaTitle>
<CredenzaDescription>
Set a pincode to protect this resource
</CredenzaDescription>
</CredenzaHeader>
<CredenzaBody>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4"
id="set-pincode-form"
>
<FormField
control={form.control}
name="pincode"
render={({ field }) => (
<FormItem>
<FormLabel>PIN Code</FormLabel>
<FormControl>
<div className="flex justify-center">
<InputOTP
autoComplete="false"
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>
<FormDescription>
Users will be able to access
this resource by entering this
PIN code. It must be at least 6
digits long.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</form>
</Form>
</CredenzaBody>
<CredenzaFooter>
<Button
type="submit"
form="set-pincode-form"
loading={loading}
disabled={loading}
>
Enable PIN Code Protection
</Button>
<CredenzaClose asChild>
<Button variant="outline">Close</Button>
</CredenzaClose>
</CredenzaFooter>
</CredenzaContent>
</Credenza>
</>
);
}

View File

@@ -32,9 +32,10 @@ import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
import { ListUsersResponse } from "@server/routers/user";
import { Switch } from "@app/components/ui/switch";
import { Label } from "@app/components/ui/label";
import { ShieldCheck } from "lucide-react";
import { Binary, Key, ShieldCheck } from "lucide-react";
import SetResourcePasswordForm from "./components/SetResourcePasswordForm";
import { Separator } from "@app/components/ui/separator";
import SetResourcePincodeForm from "./components/SetResourcePincodeForm";
const UsersRolesFormSchema = z.object({
roles: z.array(
@@ -78,8 +79,11 @@ export default function ResourceAuthenticationPage() {
const [loadingSaveUsersRoles, setLoadingSaveUsersRoles] = useState(false);
const [loadingRemoveResourcePassword, setLoadingRemoveResourcePassword] =
useState(false);
const [loadingRemoveResourcePincode, setLoadingRemoveResourcePincode] =
useState(false);
const [isSetPasswordOpen, setIsSetPasswordOpen] = useState(false);
const [isSetPincodeOpen, setIsSetPincodeOpen] = useState(false);
const usersRolesForm = useForm<z.infer<typeof UsersRolesFormSchema>>({
resolver: zodResolver(UsersRolesFormSchema),
@@ -237,6 +241,36 @@ export default function ResourceAuthenticationPage() {
.finally(() => setLoadingRemoveResourcePassword(false));
}
function removeResourcePincode() {
setLoadingRemoveResourcePincode(true);
api.post(`/resource/${resource.resourceId}/pincode`, {
pincode: null,
})
.then(() => {
toast({
title: "Resource pincode removed",
description:
"The resource password has been removed successfully",
});
updateAuthInfo({
pincode: false,
});
})
.catch((e) => {
toast({
variant: "destructive",
title: "Error removing resource pincode",
description: formatAxiosError(
e,
"An error occurred while removing the resource pincode",
),
});
})
.finally(() => setLoadingRemoveResourcePincode(false));
}
if (pageLoading) {
return <></>;
}
@@ -257,6 +291,20 @@ export default function ResourceAuthenticationPage() {
/>
)}
{isSetPincodeOpen && (
<SetResourcePincodeForm
open={isSetPincodeOpen}
setOpen={setIsSetPincodeOpen}
resourceId={resource.resourceId}
onSetPincode={() => {
setIsSetPincodeOpen(false);
updateAuthInfo({
pincode: true,
});
}}
/>
)}
<div className="space-y-12">
<section className="space-y-8">
<SettingsSectionTitle
@@ -412,40 +460,78 @@ export default function ResourceAuthenticationPage() {
<Separator />
<section className="space-y-8">
<section className="space-y-8 lg:max-w-2xl">
<SettingsSectionTitle
title="Authentication Methods"
description="Allow anyone to access the resource via the below methods"
size="1xl"
/>
{authInfo?.password ? (
<div className="flex items-center space-x-4">
<div className="flex items-center text-green-500 space-x-2">
<ShieldCheck />
<span>Password Protection Enabled</span>
<div className="flex flex-col space-y-4">
<div className="flex items-center justify-between space-x-4">
<div
className={`flex items-center text-${!authInfo.password ? "red" : "green"}-500 space-x-2`}
>
<Key />
<span>
Password Protection{" "}
{authInfo?.password
? "Enabled"
: "Disabled"}
</span>
</div>
<Button
variant="gray"
type="button"
loading={loadingRemoveResourcePassword}
disabled={loadingRemoveResourcePassword}
onClick={removeResourcePassword}
>
Remove Password
</Button>
{authInfo?.password ? (
<Button
variant="gray"
type="button"
loading={loadingRemoveResourcePassword}
disabled={loadingRemoveResourcePassword}
onClick={removeResourcePassword}
>
Remove Password
</Button>
) : (
<Button
variant="gray"
type="button"
onClick={() => setIsSetPasswordOpen(true)}
>
Add Password
</Button>
)}
</div>
) : (
<div>
<Button
variant="gray"
type="button"
onClick={() => setIsSetPasswordOpen(true)}
<div className="flex items-center justify-between space-x-4">
<div
className={`flex items-center text-${!authInfo.pincode ? "red" : "green"}-500 space-x-2`}
>
Add Password
</Button>
<Binary />
<span>
PIN Code Protection{" "}
{authInfo?.pincode ? "Enabled" : "Disabled"}
</span>
</div>
{authInfo?.pincode ? (
<Button
variant="gray"
type="button"
loading={loadingRemoveResourcePincode}
disabled={loadingRemoveResourcePincode}
onClick={removeResourcePincode}
>
Remove PIN Code
</Button>
) : (
<Button
variant="gray"
type="button"
onClick={() => setIsSetPincodeOpen(true)}
>
Add PIN Code
</Button>
)}
</div>
)}
</div>
</section>
</div>
</>