basic auth portal save

This commit is contained in:
Milo Schwartz 2024-11-23 16:36:07 -05:00
parent f9e0c33368
commit 0b3ca5f999
No known key found for this signature in database
12 changed files with 511 additions and 269 deletions

View file

@ -90,7 +90,7 @@ export async function verifyResourceSession(
return allowed(res);
}
const redirectUrl = `${config.app.base_url}/${resource.orgId}/auth/resource/${resource.resourceId}?redirect=${originalRequestURL}`;
const redirectUrl = `${config.app.base_url}/${resource.orgId}/auth/resource/${resource.resourceId}?r=${originalRequestURL}`;
if (sso && sessions.session) {
const { session, user } = await validateSessionToken(

View file

@ -23,12 +23,13 @@ export type GetResourceAuthInfoResponse = {
pincode: boolean;
sso: boolean;
blockAccess: boolean;
url: string;
};
export async function getResourceAuthInfo(
req: Request,
res: Response,
next: NextFunction
next: NextFunction,
): Promise<any> {
try {
const parsedParams = getResourceAuthInfoSchema.safeParse(req.params);
@ -36,8 +37,8 @@ export async function getResourceAuthInfo(
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
fromError(parsedParams.error).toString(),
),
);
}
@ -48,11 +49,11 @@ export async function getResourceAuthInfo(
.from(resources)
.leftJoin(
resourcePincode,
eq(resourcePincode.resourceId, resources.resourceId)
eq(resourcePincode.resourceId, resources.resourceId),
)
.leftJoin(
resourcePassword,
eq(resourcePassword.resourceId, resources.resourceId)
eq(resourcePassword.resourceId, resources.resourceId),
)
.where(eq(resources.resourceId, resourceId))
.limit(1);
@ -61,9 +62,11 @@ export async function getResourceAuthInfo(
const pincode = result?.resourcePincode;
const password = result?.resourcePassword;
const url = `${resource.ssl ? "https" : "http"}://${resource.fullDomain}`;
if (!resource) {
return next(
createHttpError(HttpCode.NOT_FOUND, "Resource not found")
createHttpError(HttpCode.NOT_FOUND, "Resource not found"),
);
}
@ -75,6 +78,7 @@ export async function getResourceAuthInfo(
pincode: pincode !== null,
sso: resource.sso,
blockAccess: resource.blockAccess,
url,
},
success: true,
error: false,
@ -83,7 +87,10 @@ export async function getResourceAuthInfo(
});
} catch (error) {
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"An error occurred",
),
);
}
}

View file

@ -31,7 +31,7 @@ const updateResourceBodySchema = z
export async function updateResource(
req: Request,
res: Response,
next: NextFunction
next: NextFunction,
): Promise<any> {
try {
const parsedParams = updateResourceParamsSchema.safeParse(req.params);
@ -39,8 +39,8 @@ export async function updateResource(
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
fromError(parsedParams.error).toString(),
),
);
}
@ -49,8 +49,8 @@ export async function updateResource(
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
fromError(parsedBody.error).toString(),
),
);
}
@ -67,8 +67,8 @@ export async function updateResource(
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Resource with ID ${resourceId} not found`
)
`Resource with ID ${resourceId} not found`,
),
);
}
@ -76,16 +76,23 @@ export async function updateResource(
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Resource does not have a domain"
)
"Resource does not have a domain",
),
);
}
const fullDomain = `${updateData.subdomain}.${resource[0].orgs.domain}`;
const fullDomain = updateData.subdomain
? `${updateData.subdomain}.${resource[0].orgs.domain}`
: undefined;
const updatePayload = {
...updateData,
...(fullDomain && { fullDomain }),
};
const updatedResource = await db
.update(resources)
.set({ ...updateData, fullDomain })
.set(updatePayload)
.where(eq(resources.resourceId, resourceId))
.returning();
@ -93,8 +100,8 @@ export async function updateResource(
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Resource with ID ${resourceId} not found`
)
`Resource with ID ${resourceId} not found`,
),
);
}
@ -108,7 +115,10 @@ export async function updateResource(
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"An error occurred",
),
);
}
}

View file

@ -29,6 +29,12 @@ import {
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";
const pinSchema = z.object({
pin: z
@ -40,16 +46,60 @@ const pinSchema = z.object({
const passwordSchema = z.object({
password: z
.string()
.min(8, { message: "Password must be at least 8 characters long" }),
.min(1, { message: "Password must be at least 1 character long" }),
});
const userSchema = z.object({
email: z.string().email(),
password: z.string().min(1),
email: z.string().email({ message: "Please enter a valid email address" }),
password: z
.string()
.min(1, { message: "Password must be at least 1 character long" }),
});
export default function ResourceAuthPortal() {
const [activeTab, setActiveTab] = useState("pin");
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 [userError, setUserError] = useState<string | null>(null);
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),
@ -79,41 +129,81 @@ export default function ResourceAuthPortal() {
};
const onPasswordSubmit = (values: z.infer<typeof passwordSchema>) => {
console.log("Password authentication", values);
// Implement password authentication logic here
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"),
);
});
};
const handleSSOAuth = () => {
const handleSSOAuth = (values: z.infer<typeof userSchema>) => {
console.log("SSO authentication");
// Implement SSO authentication logic here
api.post<AxiosResponse<LoginResponse>>("/auth/login", {
email: values.email,
password: values.password,
})
.then((res) => {
// console.log(res)
window.location.href = props.redirect;
})
.catch((e) => {
console.error(e);
setUserError(
formatAxiosError(e, "An error occurred while logging in"),
);
});
};
return (
<div className="w-full max-w-md mx-auto">
<div>
<Card>
<CardHeader>
<CardTitle>Authentication Required</CardTitle>
<CardDescription>
Choose your preferred method
{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}>
<TabsList className="grid w-full grid-cols-3">
{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
<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">
<Form {...pinForm}>
<form
onSubmit={pinForm.handleSubmit(onPinSubmit)}
onSubmit={pinForm.handleSubmit(
onPinSubmit,
)}
className="space-y-4"
>
<FormField
@ -132,22 +222,34 @@ export default function ResourceAuthPortal() {
>
<InputOTPGroup className="flex">
<InputOTPSlot
index={0}
index={
0
}
/>
<InputOTPSlot
index={1}
index={
1
}
/>
<InputOTPSlot
index={2}
index={
2
}
/>
<InputOTPSlot
index={3}
index={
3
}
/>
<InputOTPSlot
index={4}
index={
4
}
/>
<InputOTPSlot
index={5}
index={
5
}
/>
</InputOTPGroup>
</InputOTP>
@ -157,13 +259,18 @@ export default function ResourceAuthPortal() {
</FormItem>
)}
/>
<Button type="submit" className="w-full">
<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">
<Form {...passwordForm}>
<form
@ -177,7 +284,9 @@ export default function ResourceAuthPortal() {
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormLabel>
Password
</FormLabel>
<FormControl>
<Input
placeholder="Enter password"
@ -189,24 +298,30 @@ export default function ResourceAuthPortal() {
</FormItem>
)}
/>
<Button type="submit" className="w-full">
{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">
<Form {...userForm}>
<form
onSubmit={userForm.handleSubmit(
(values) => {
console.log(
"User authentication",
values,
);
// Implement user authentication logic here
},
handleSSOAuth,
)}
className="space-y-4"
>
@ -232,7 +347,9 @@ export default function ResourceAuthPortal() {
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Password</FormLabel>
<FormLabel>
Password
</FormLabel>
<FormControl>
<Input
placeholder="Enter password"
@ -244,13 +361,24 @@ export default function ResourceAuthPortal() {
</FormItem>
)}
/>
<Button type="submit" className="w-full">
{userError && (
<Alert variant="destructive">
<AlertDescription>
{userError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
>
<LockIcon className="w-4 h-4 mr-2" />
Login as User
</Button>
</form>
</Form>
</TabsContent>
)}
</Tabs>
</CardContent>
</Card>

View file

@ -0,0 +1,24 @@
// import { Card, CardContent, CardHeader, CardTitle } from "@app/components/ui/card";
// export default async function ResourceNotFound() {
// return (
// <Card className="w-full max-w-md">
// <CardHeader>
// {/* <div className="flex items-center justify-center w-20 h-20 rounded-full bg-red-100 mx-auto mb-4">
// <XCircle
// className="w-10 h-10 text-red-600"
// aria-hidden="true"
// />
// </div> */}
// <CardTitle className="text-center text-2xl font-bold">
// Invite Not Accepted
// </CardTitle>
// </CardHeader>
// <CardContent>{renderBody()}</CardContent>
// <CardFooter className="flex justify-center space-x-4">
// {renderFooter()}
// </CardFooter>
// </Card>
// );
// }

View file

@ -1,16 +1,85 @@
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";
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;
console.log(params);
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 <>Resource not found</>;
}
const isSSOOnly = authInfo.sso && !authInfo.password && !authInfo.pincode;
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 <>You do not have access to this resource</>;
}
return (
<>
<div className="p-3 md:mt-32">
<ResourceAuthPortal />
<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

@ -415,7 +415,7 @@ export default function ResourceAuthenticationPage() {
<section className="space-y-8">
<SettingsSectionTitle
title="Authentication Methods"
description="You can also anyone to access the resource via the below methods"
description="Allow anyone to access the resource via the below methods"
size="1xl"
/>

View file

@ -39,7 +39,6 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
};
return (
<Card className="shadow-none">
<Alert>
<InfoIcon className="h-4 w-4" />
<AlertTitle className="font-semibold">
@ -54,17 +53,16 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
<div className="flex items-center space-x-2 text-green-500">
<ShieldCheck />
<span>
This resource is protected with at least
one auth method.
This resource is protected with at least one
auth method.
</span>
</div>
) : (
<div className="flex items-center space-x-2 text-yellow-500">
<ShieldOff />
<span>
This resource is not protected with any
auth method. Anyone can access this
resource.
This resource is not protected with any auth
method. Anyone can access this resource.
</span>
</div>
)}
@ -111,6 +109,5 @@ export default function ResourceInfoBox({}: ResourceInfoBoxType) {
</div>
</AlertDescription>
</Alert>
</Card>
);
}

View file

@ -99,12 +99,12 @@ export default function InviteStatusCard({
<div className="p-3 md:mt-32 flex items-center justify-center">
<Card className="w-full max-w-md">
<CardHeader>
<div className="flex items-center justify-center w-20 h-20 rounded-full bg-red-100 mx-auto mb-4">
{/* <div className="flex items-center justify-center w-20 h-20 rounded-full bg-red-100 mx-auto mb-4">
<XCircle
className="w-10 h-10 text-red-600"
aria-hidden="true"
/>
</div>
</div> */}
<CardTitle className="text-center text-2xl font-bold">
Invite Not Accepted
</CardTitle>

View file

@ -4,7 +4,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const alertVariants = cva(
"relative w-full rounded-lg p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {

View file

@ -1,6 +1,6 @@
import * as React from "react"
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const Card = React.forwardRef<
HTMLDivElement,
@ -9,13 +9,13 @@ const Card = React.forwardRef<
<div
ref={ref}
className={cn(
"rounded-lg border bg-card text-card-foreground shadow-sm",
className
"rounded-lg border bg-card text-card-foreground",
className,
)}
{...props}
/>
))
Card.displayName = "Card"
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<
HTMLDivElement,
@ -26,8 +26,8 @@ const CardHeader = React.forwardRef<
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<
HTMLParagraphElement,
@ -37,12 +37,12 @@ const CardTitle = React.forwardRef<
ref={ref}
className={cn(
"text-2xl font-semibold leading-none tracking-tight",
className
className,
)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLParagraphElement,
@ -53,16 +53,16 @@ const CardDescription = React.forwardRef<
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<
HTMLDivElement,
@ -73,7 +73,14 @@ const CardFooter = React.forwardRef<
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
));
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent,
};

View file

@ -29,7 +29,7 @@ const TabsTrigger = React.forwardRef<
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground",
className
)}
{...props}