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 endpoints for authorize, token

Kiran Kfe4417fe8739
diff --git a/apps/web/app/api/oauth-apps/[appId]/route.ts b/apps/web/app/api/oauth-apps/[appId]/route.ts
index c6e3bd9edc..9b663d7230 100644
--- a/apps/web/app/api/oauth-apps/[appId]/route.ts
+++ b/apps/web/app/api/oauth-apps/[appId]/route.ts
@@ -2,10 +2,7 @@ import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import {
- oAuthAppSchema,
- updateOAuthAppSchema,
-} from "@/lib/zod/schemas/oauth-app";
+import { oAuthAppSchema, updateOAuthAppSchema } from "@/lib/zod/schemas/oauth";
import { NextResponse } from "next/server";
// GET /api/oauth-apps/[appId] – get an OAuth app
diff --git a/apps/web/app/api/oauth-apps/route.ts b/apps/web/app/api/oauth-apps/route.ts
index 5bd55bd6ed..a9e22d129a 100644
--- a/apps/web/app/api/oauth-apps/route.ts
+++ b/apps/web/app/api/oauth-apps/route.ts
@@ -2,10 +2,7 @@ import { TOKEN_LENGTHS } from "@/lib/api/oauth";
import { parseRequestBody } from "@/lib/api/utils";
import { hashToken, withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import {
- createOAuthAppSchema,
- oAuthAppSchema,
-} from "@/lib/zod/schemas/oauth-app";
+import { createOAuthAppSchema, oAuthAppSchema } from "@/lib/zod/schemas/oauth";
import { nanoid } from "@dub/utils";
import { NextResponse } from "next/server";
import { z } from "zod";
diff --git a/apps/web/app/api/oauth/token/route.ts b/apps/web/app/api/oauth/token/route.ts
new file mode 100644
index 0000000000..fbed3c9900
--- /dev/null
+++ b/apps/web/app/api/oauth/token/route.ts
@@ -0,0 +1,67 @@
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { TOKEN_EXPIRY, TOKEN_LENGTHS } from "@/lib/api/oauth";
+import { hashToken } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { codeExchangeSchema } from "@/lib/zod/schemas/oauth";
+import { getCurrentPlan, nanoid } from "@dub/utils";
+import { NextRequest, NextResponse } from "next/server";
+
+// POST /api/oauth/token - exchange `code` for an access token
+export async function POST(req: NextRequest) {
+ try {
+ // Decode application/x-www-form-urlencoded body
+ const formData = Object.fromEntries(await req.formData());
+ console.log("/api/oauth/token", formData)
+ const { client_id, client_secret, code, redirect_uri } =
+ codeExchangeSchema.parse(formData);
+
+ const oauthCode = await prisma.oAuthCode.findFirst({
+ where: {
+ code,
+ clientId: client_id,
+ redirectUri: redirect_uri,
+ app: {
+ clientSecretHashed: await hashToken(client_secret),
+ },
+ },
+ });
+
+ if (!oauthCode) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Invalid code",
+ });
+ }
+
+ const accessToken = `dub_${nanoid(TOKEN_LENGTHS.accessToken)}`;
+ const hashedKey = await hashToken(accessToken);
+ const partialKey = `${accessToken.slice(0, 3)}...${accessToken.slice(-4)}`;
+
+ const { expires } = await prisma.restrictedToken.create({
+ data: {
+ name: `OAuth2.0 Access Token`,
+ hashedKey,
+ partialKey,
+ userId: oauthCode.userId,
+ projectId: oauthCode.projectId,
+ rateLimit: getCurrentPlan("free").limits.api,
+ expires: new Date(Date.now() + TOKEN_EXPIRY.accessToken),
+ scopes: "",
+ // scopes && scopes.length > 0 ? [...new Set(scopes)].join(" ") : null,
+ },
+ });
+
+ const response = {
+ access_token: accessToken,
+ token_type: "Bearer",
+ expires_in: expires,
+ scope: "read write",
+ };
+
+ console.log("response", response);
+
+ return NextResponse.json(response);
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/api/oauth/userinfo/route.ts b/apps/web/app/api/oauth/userinfo/route.ts
new file mode 100644
index 0000000000..e885a6d086
--- /dev/null
+++ b/apps/web/app/api/oauth/userinfo/route.ts
@@ -0,0 +1,13 @@
+import { NextRequest, NextResponse } from "next/server";
+
+// POST /api/oauth/token - exchange `code` for an access token
+export async function GET(req: NextRequest) {
+ const response = {
+ id: "xxx",
+ email: "[email protected]",
+ name: "Kiran",
+ avatar_url: null,
+ };
+
+ return NextResponse.json(response);
+}
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
new file mode 100644
index 0000000000..97100cb019
--- /dev/null
+++ b/apps/web/app/app.dub.co/(auth)/oauth/authorize/page.tsx
@@ -0,0 +1,149 @@
+import { TOKEN_LENGTHS } from "@/lib/api/oauth";
+import { getSession } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import z from "@/lib/zod";
+import { authorizeSchema } from "@/lib/zod/schemas/oauth";
+import { Background, Button, Footer, Nav } from "@dub/ui";
+import { nanoid } from "@dub/utils";
+import { TimerOff } from "lucide-react";
+import { redirect } from "next/navigation";
+
+// 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 runtime = "nodejs";
+
+export default async function Authorize({
+ searchParams,
+}: {
+ searchParams?: z.infer<typeof authorizeSchema>;
+}) {
+ const session = await getSession();
+
+ if (!session) {
+ redirect("/login");
+ }
+
+ const result = authorizeSchema.safeParse(searchParams);
+
+ if (!result.success) {
+ return result.error.message;
+ }
+
+ const { client_id, redirect_uri, response_type, state } = result.data;
+
+ const app = await prisma.oAuthApp.findFirst({
+ where: {
+ clientId: client_id,
+ },
+ });
+
+ if (!app) {
+ return `Could not find OAuth client with clientId ${client_id}`;
+ }
+
+ // Validate
+ if (app.redirectUri !== redirect_uri) {
+ return "Invalid redirect_uri parameter for the application.";
+ }
+
+ const workspaces = await prisma.project.findMany({
+ where: {
+ users: {
+ some: {
+ userId: session.user.id,
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ logo: true,
+ },
+ });
+
+ return (
+ <main className="flex min-h-screen flex-col justify-between">
+ <Nav />
+ <div className="z-10 mx-2 my-10 flex max-w-md flex-col items-center space-y-5 px-2.5 text-center sm:mx-auto sm:max-w-lg sm:px-0 lg:mb-16">
+ <div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full border border-gray-300 bg-white/30">
+ <TimerOff className="h-6 w-6 text-gray-400" />
+ </div>
+ <h1 className="font-display text-5xl font-bold">{app.name}</h1>
+ <p className="text-lg text-gray-600">{}</p>
+ <form action={handleAuthorize}>
+ <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} />
+
+ <select name="workspace_id">
+ {workspaces.map((workspace) => (
+ <option key={workspace.id} value={workspace.id}>
+ <div>
+ <img
+ src={workspace.logo!}
+ className="h-8 w-8 rounded-full"
+ alt=""
+ />
+ {workspace.name}
+ </div>
+ </option>
+ ))}
+ </select>
+ <Button
+ text={`Authorize ${app.name}`}
+ type="submit"
+ // loading={clickedGithub}
+ // icon={<Github className="h-4 w-4" />}
+ />
+ </form>
+ </div>
+ <Footer />
+ <Background />
+ </main>
+ );
+}
+
+// Server action to create OAuth app
+const handleAuthorize = async (formData: FormData) => {
+ "use server";
+
+ const session = await getSession();
+
+ if (!session) {
+ return redirect("/login");
+ }
+
+ const { client_id, redirect_uri, response_type, state, workspace_id } =
+ authorizeSchema
+ .merge(
+ z.object({
+ workspace_id: z.string(),
+ }),
+ )
+ .parse(Object.fromEntries(formData));
+
+ const { code } = await prisma.oAuthCode.create({
+ data: {
+ clientId: client_id,
+ projectId: workspace_id,
+ redirectUri: redirect_uri,
+ userId: session.user.id,
+ scopes: "",
+ code: nanoid(TOKEN_LENGTHS.code),
+ expiresAt: new Date(),
+ },
+ });
+
+ const searchParams = new URLSearchParams({
+ code,
+ ...(state && { state }),
+ });
+
+ return redirect(`${redirect_uri}?${searchParams.toString()}`);
+};
diff --git a/apps/web/lib/api/oauth.ts b/apps/web/lib/api/oauth.ts
index 188c2d5c56..0d4339525b 100644
--- a/apps/web/lib/api/oauth.ts
+++ b/apps/web/lib/api/oauth.ts
@@ -1,6 +1,7 @@
export const TOKEN_LENGTHS = {
clientId: 32,
clientSecret: 40,
+ code: 64,
accessToken: 64,
refreshToken: 64,
};
diff --git a/apps/web/lib/zod/schemas/oauth-app.ts b/apps/web/lib/zod/schemas/oauth.ts
similarity index 85%
rename from apps/web/lib/zod/schemas/oauth-app.ts
rename to apps/web/lib/zod/schemas/oauth.ts
index fec0553f56..7378dc08de 100644
--- a/apps/web/lib/zod/schemas/oauth-app.ts
+++ b/apps/web/lib/zod/schemas/oauth.ts
@@ -1,3 +1,4 @@
+import { availableScopes } from "@/lib/api/tokens/scopes";
import { z } from "zod";
export const oAuthAppSchema = z.object({
@@ -6,7 +7,10 @@ export const oAuthAppSchema = z.object({
description: z.string().nullable(),
website: z.string(),
redirectUri: z.string(),
- scopes: z.array(z.string()).nullable(),
+ scopes: z
+ .string()
+ .nullable()
+ .transform((val) => val?.split(" ") ?? []),
clientId: z.string(),
});
@@ -15,13 +19,13 @@ export const createOAuthAppSchema = z.object({
description: z.string().max(255).nullable(),
website: z.string().url().max(255),
redirectUri: z.string().url().max(255),
- scopes: z.array(z.string()).nullable(), // TODO: validate scopes and should be array
+ scopes: z.array(z.enum(availableScopes)).default([]).optional(),
});
export const updateOAuthAppSchema = createOAuthAppSchema.partial();
-// Schema for OAuth2.0 Authorization code request
-export const authRequestSchema = z.object({
+// Schema for OAuth2.0 Authorization request
+export const authorizeSchema = 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", {
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index d60dcf7d8c..eaa60d2775 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -397,7 +397,8 @@ model OAuthApp {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ Codes OAuthCode[]
@@index(projectId)
}
@@ -412,4 +413,6 @@ model OAuthCode {
redirectUri String
expiresAt DateTime
createdAt DateTime @default(now())
+
+ app OAuthApp @relation(fields: [clientId], references: [id], onDelete: Cascade)
}