Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

add endpoint to authorize the request and create the access code

Kiran K9ed785a719e3
diff --git a/apps/web/app/api/oauth/authorize/route.ts b/apps/web/app/api/oauth/authorize/route.ts
new file mode 100644
index 0000000000..35f590106a
--- /dev/null
+++ b/apps/web/app/api/oauth/authorize/route.ts
@@ -0,0 +1,58 @@
+import { TOKEN_EXPIRY, TOKEN_LENGTH } from "@/lib/api/oauth";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withSession } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { approveAuthorizeRequestSchema } from "@/lib/zod/schemas/oauth";
+import { nanoid } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+// POST /api/oauth/authorize - approve OAuth authorization request
+export const POST = withSession(async ({ session, req }) => {
+ const body = approveAuthorizeRequestSchema.parse(await parseRequestBody(req));
+ const { state, client_id: clientId, redirect_uri: redirectUri } = body;
+ let { workspaceId } = body;
+
+ workspaceId = workspaceId.replace("ws_", "");
+
+ const oAuthClient = await prisma.oAuthClient.findUniqueOrThrow({
+ where: {
+ clientId,
+ },
+ });
+
+ await prisma.project.findUniqueOrThrow({
+ where: {
+ id: workspaceId,
+ },
+ });
+
+ console.info("Authorize request", {
+ workspaceId,
+ state,
+ clientId,
+ redirectUri,
+ });
+
+ const { code } = await prisma.oAuthCode.create({
+ data: {
+ clientId,
+ redirectUri,
+ projectId: workspaceId,
+ userId: session.user.id,
+ scopes: oAuthClient.scopes,
+ code: nanoid(TOKEN_LENGTH.code),
+ expiresAt: new Date(Date.now() + TOKEN_EXPIRY.code),
+ },
+ });
+
+ const searchParams = new URLSearchParams({
+ code,
+ ...(state && { state }),
+ });
+
+ const response = {
+ callbackUrl: `${redirectUri}?${searchParams.toString()}`,
+ };
+
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-form.tsx b/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-form.tsx
index 829e5866a2..0802dcf7d4 100644
--- a/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-form.tsx
+++ b/apps/web/app/app.dub.co/(auth)/oauth/authorize/authorize-form.tsx
@@ -1,15 +1,15 @@
"use client";
-import { handleAuthorize } from "@/lib/oauth";
import useWorkspaces from "@/lib/swr/use-workspaces";
import z from "@/lib/zod";
-import { authorizeSchema } from "@/lib/zod/schemas/oauth";
+import { authorizeRequestSchema } from "@/lib/zod/schemas/oauth";
import { Button, InputSelect, InputSelectItemProps } from "@dub/ui";
import { DICEBEAR_AVATAR_URL } from "@dub/utils";
import { OAuthClient } from "@prisma/client";
import { useMemo, useState } from "react";
+import { toast } from "sonner";
-interface AuthorizeFormProps extends z.infer<typeof authorizeSchema> {
+interface AuthorizeFormProps extends z.infer<typeof authorizeRequestSchema> {
oAuthClient: Pick<OAuthClient, "name">;
}
@@ -17,6 +17,7 @@ export const AuthorizeForm = (props: AuthorizeFormProps) => {
const { oAuthClient, client_id, redirect_uri, response_type, state } = props;
const { workspaces } = useWorkspaces();
+ const [submitting, setSubmitting] = useState(false);
const [selectedWorkspace, setSelectedWorkspace] =
useState<InputSelectItemProps | null>(null);
@@ -30,8 +31,8 @@ export const AuthorizeForm = (props: AuthorizeFormProps) => {
: [];
}, [workspaces]);
- // Decline
- const handleDecline = () => {
+ // Decline the request
+ const onDecline = () => {
const searchParams = new URLSearchParams({
error: "access_denied",
...(state && { state }),
@@ -40,17 +41,34 @@ export const AuthorizeForm = (props: AuthorizeFormProps) => {
window.location.href = `${redirect_uri}?${searchParams.toString()}`;
};
+ // Approve the
+ const onAuthorize = async (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+ setSubmitting(true);
+
+ const response = await fetch("/api/oauth/authorize", {
+ method: "POST",
+ body: JSON.stringify(Object.fromEntries(new FormData(e.currentTarget))),
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ setSubmitting(false);
+ toast.error(data.error.message);
+ return;
+ }
+
+ window.location.href = data.callbackUrl;
+ };
+
return (
- <form action={handleAuthorize}>
+ <form onSubmit={onAuthorize}>
<input type="hidden" name="client_id" value={client_id} />
<input type="hidden" name="redirect_uri" value={redirect_uri} />
<input type="hidden" name="response_type" value={response_type} />
<input type="hidden" name="state" value={state} />
- <input
- type="hidden"
- name="workspaceId"
- value={selectedWorkspace?.id.replace("ws_", "")}
- />
+ <input type="hidden" name="workspaceId" value={selectedWorkspace?.id} />
<p className="text-sm text-gray-500">
Select a workspace to grant API access to
</p>
@@ -60,18 +78,21 @@ export const AuthorizeForm = (props: AuthorizeFormProps) => {
selectedItem={selectedWorkspace}
setSelectedItem={setSelectedWorkspace}
adjustForMobile
+ disabled={submitting}
/>
</div>
<div className="mt-4 flex justify-between gap-4">
<Button
text="Decline"
type="button"
- onClick={handleDecline}
+ onClick={onDecline}
variant="secondary"
+ disabled={submitting}
/>
<Button
text={`Authorize ${oAuthClient.name}`}
type="submit"
+ loading={submitting}
disabled={!selectedWorkspace}
disabledTooltip={
!selectedWorkspace ? "Please select a workspace to continue" : ""
diff --git a/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx b/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx
index eb16733951..89b1366514 100644
--- a/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx
+++ b/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx
@@ -1,9 +1,9 @@
import { getSession } from "@/lib/auth";
import { vaidateAuthorizeRequest } from "@/lib/oauth";
import z from "@/lib/zod";
-import { authorizeSchema } from "@/lib/zod/schemas/oauth";
+import { authorizeRequestSchema } from "@/lib/zod/schemas/oauth";
import { Logo } from "@dub/ui";
-import { HOME_DOMAIN } from "@dub/utils";
+import { HOME_DOMAIN, constructMetadata } from "@dub/utils";
import { ArrowLeftRight } from "lucide-react";
import { redirect } from "next/navigation";
import { Suspense } from "react";
@@ -12,17 +12,15 @@ import { ScopesRequested } from "./scopes-requested";
export const runtime = "nodejs";
-// export const metadata = constructMetadata({
-// title: "Expired Link – Dub.co",
-// description:
-// "This link has expired. Please contact the owner of this link to get a new one.",
-// noIndex: true,
-// });
+export const metadata = constructMetadata({
+ title: "Authorize API access | Dub",
+ noIndex: true,
+});
export default async function Authorize({
searchParams,
}: {
- searchParams?: z.infer<typeof authorizeSchema>;
+ searchParams?: z.infer<typeof authorizeRequestSchema>;
}) {
const session = await getSession();
diff --git a/apps/web/lib/api/errors.ts b/apps/web/lib/api/errors.ts
index 9f97b7e4db..cca064953f 100644
--- a/apps/web/lib/api/errors.ts
+++ b/apps/web/lib/api/errors.ts
@@ -145,7 +145,10 @@ export function handleApiError(error: any): ErrorResponse & { status: number } {
return {
error: {
code: "not_found",
- message: `${error.meta.cause} Please check the provided identifier.`,
+ message:
+ error?.meta?.cause ||
+ error.message ||
+ "The requested resource was not found.",
doc_url: `${docErrorUrl}#not-found`,
},
status: 404,
diff --git a/apps/web/lib/oauth.ts b/apps/web/lib/oauth.ts
index 99a84a83fe..b42c396234 100644
--- a/apps/web/lib/oauth.ts
+++ b/apps/web/lib/oauth.ts
@@ -1,14 +1,10 @@
"use server";
import { prisma } from "@/lib/prisma";
-import { nanoid } from "@dub/utils";
-import { redirect } from "next/navigation";
-import { TOKEN_EXPIRY, TOKEN_LENGTH } from "./api/oauth";
-import { getSession } from "./auth";
-import { authorizeSchema } from "./zod/schemas/oauth";
+import { authorizeRequestSchema } from "./zod/schemas/oauth";
export const vaidateAuthorizeRequest = async (params: any) => {
- const request = authorizeSchema.parse(params);
+ const request = authorizeRequestSchema.parse(params);
const { client_id: clientId, redirect_uri: redirectUri } = request;
const oAuthClient = await prisma.oAuthClient.findFirst({
@@ -30,43 +26,3 @@ export const vaidateAuthorizeRequest = async (params: any) => {
request,
};
};
-
-// Handle the authorize request and create a new OAuth code
-export const handleAuthorize = async (formData: FormData) => {
- const session = await getSession();
-
- if (!session) {
- return redirect("/login");
- }
-
- const workspaceId = formData.get("workspaceId");
-
- if (!workspaceId) {
- throw new Error("Please select a workspace to authorize the app");
- }
-
- const { oAuthClient, request } = await vaidateAuthorizeRequest(
- Object.fromEntries(formData),
- );
-
- console.info("Authorize request", { ...request, workspaceId });
-
- const { code } = await prisma.oAuthCode.create({
- data: {
- clientId: request.client_id,
- redirectUri: request.redirect_uri,
- projectId: workspaceId as string,
- userId: session.user.id,
- scopes: oAuthClient.scopes,
- code: nanoid(TOKEN_LENGTH.code),
- expiresAt: new Date(Date.now() + TOKEN_EXPIRY.code),
- },
- });
-
- const searchParams = new URLSearchParams({
- code,
- ...(request.state && { state: request.state }),
- });
-
- return redirect(`${request.redirect_uri}?${searchParams.toString()}`);
-};
diff --git a/apps/web/lib/zod/schemas/oauth.ts b/apps/web/lib/zod/schemas/oauth.ts
index b8fdf49b46..9baa370080 100644
--- a/apps/web/lib/zod/schemas/oauth.ts
+++ b/apps/web/lib/zod/schemas/oauth.ts
@@ -24,7 +24,7 @@ export const createOAuthClientSchema = z.object({
export const updateOAuthClientSchema = createOAuthClientSchema.partial();
// Schema for OAuth2.0 Authorization request
-export const authorizeSchema = z.object({
+export const authorizeRequestSchema = z.object({
client_id: z.string().min(1, "Missing client_id"),
redirect_uri: z.string().url({ message: "redirect_uri must be a valid URL" }),
response_type: z.string().refine((responseType) => responseType === "code", {
@@ -33,6 +33,13 @@ export const authorizeSchema = z.object({
state: z.string().max(255).optional(),
});
+// Aprove OAuth2.0 Authorization request
+export const approveAuthorizeRequestSchema = authorizeRequestSchema.extend({
+ workspaceId: z
+ .string()
+ .min(1, "Please select a workspace to authorize the app"),
+});
+
// Schema for OAuth2.0 code exchange request
export const authCodeExchangeSchema = z.object({
grant_type: z.literal("authorization_code"),