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.

refactor: Improve OAuth token route and user info route

Kiran K31353a20ee19
diff --git a/apps/web/app/api/oauth/token/route.ts b/apps/web/app/api/oauth/token/route.ts
index fbed3c9900..46e4282931 100644
--- a/apps/web/app/api/oauth/token/route.ts
+++ b/apps/web/app/api/oauth/token/route.ts
@@ -1,6 +1,6 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { TOKEN_EXPIRY, TOKEN_LENGTHS } from "@/lib/api/oauth";
-import { hashToken } from "@/lib/auth";
+import { getAuthTokenOrThrow, hashToken } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { codeExchangeSchema } from "@/lib/zod/schemas/oauth";
import { getCurrentPlan, nanoid } from "@dub/utils";
@@ -9,19 +9,48 @@ 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);
+ let clientId = client_id;
+ let clientSecret = client_secret;
+
+ if (!client_id && !client_secret) {
+ // came in the format {client_id}:{client_secret}
+ const token = getAuthTokenOrThrow(req, "Basic");
+ const splits = Buffer.from(token, "base64").toString("utf-8").split(":");
+
+ if (splits.length > 1) {
+ clientId = splits[0];
+ clientSecret = splits[1];
+ }
+ }
+
+ if (!clientId || !clientSecret) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Invalid client credentials",
+ });
+ }
+
const oauthCode = await prisma.oAuthCode.findFirst({
where: {
code,
clientId: client_id,
redirectUri: redirect_uri,
app: {
- clientSecretHashed: await hashToken(client_secret),
+ clientSecretHashed: await hashToken(clientSecret),
+ },
+ },
+ select: {
+ userId: true,
+ projectId: true,
+ app: {
+ select: {
+ id: true,
+ name: true,
+ },
},
},
});
@@ -33,13 +62,19 @@ export async function POST(req: NextRequest) {
});
}
+ await prisma.oAuthCode.delete({
+ where: {
+ 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`,
+ name: `Access token for ${oauthCode.app.name}`,
hashedKey,
partialKey,
userId: oauthCode.userId,
@@ -51,16 +86,13 @@ export async function POST(req: NextRequest) {
},
});
- const response = {
+ return NextResponse.json({
access_token: accessToken,
token_type: "Bearer",
expires_in: expires,
scope: "read write",
- };
-
- console.log("response", response);
-
- return NextResponse.json(response);
+ refresh_token: accessToken,
+ });
} 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
index e885a6d086..9c309f332c 100644
--- a/apps/web/app/api/oauth/userinfo/route.ts
+++ b/apps/web/app/api/oauth/userinfo/route.ts
@@ -1,13 +1,46 @@
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { getAuthTokenOrThrow, hashToken } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
import { NextRequest, NextResponse } from "next/server";
-// POST /api/oauth/token - exchange `code` for an access token
+// GET /api/oauth/userinfo - get user info by access token
export async function GET(req: NextRequest) {
- const response = {
- id: "xxx",
- email: "[email protected]",
- name: "Kiran",
- avatar_url: null,
- };
-
- return NextResponse.json(response);
+ try {
+ const accessToken = getAuthTokenOrThrow(req);
+
+ const tokenRecord = await prisma.restrictedToken.findFirst({
+ where: {
+ hashedKey: await hashToken(accessToken),
+ },
+ select: {
+ id: true,
+ user: {
+ select: {
+ id: true,
+ email: true,
+ name: true,
+ image: true,
+ },
+ },
+ },
+ });
+
+ if (!tokenRecord) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Access token not found or expired.",
+ });
+ }
+
+ const { user } = tokenRecord;
+
+ return NextResponse.json({
+ id: user.id,
+ email: user.email,
+ name: user.name,
+ avatar_url: user.image,
+ });
+ } catch (e) {
+ return handleAndReturnErrorResponse(e);
+ }
}
diff --git a/apps/web/lib/auth/utils.ts b/apps/web/lib/auth/utils.ts
index aba4976ff8..79bbcd08a5 100644
--- a/apps/web/lib/auth/utils.ts
+++ b/apps/web/lib/auth/utils.ts
@@ -1,4 +1,6 @@
import { getServerSession } from "next-auth/next";
+import { NextRequest } from "next/server";
+import { DubApiError } from "../api/errors";
import { authOptions } from "./options";
export interface Session {
@@ -14,3 +16,20 @@ export interface Session {
export const getSession = async () => {
return getServerSession(authOptions) as Promise<Session>;
};
+
+export const getAuthTokenOrThrow = (
+ req: Request | NextRequest,
+ type: "Bearer" | "Basic" = "Bearer",
+) => {
+ const authorizationHeader = req.headers.get("Authorization");
+
+ if (!authorizationHeader) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",
+ });
+ }
+
+ return authorizationHeader.replace(`${type} `, "");
+};
diff --git a/apps/web/lib/zod/schemas/oauth.ts b/apps/web/lib/zod/schemas/oauth.ts
index 7378dc08de..1a1a130665 100644
--- a/apps/web/lib/zod/schemas/oauth.ts
+++ b/apps/web/lib/zod/schemas/oauth.ts
@@ -36,8 +36,8 @@ export const authorizeSchema = z.object({
// Schema for OAuth2.0 code exchange request
export const codeExchangeSchema = z.object({
- client_id: z.string().min(1, "Missing client_id"),
- client_secret: z.string().min(1, "Missing client_secret"),
+ client_id: z.string().optional(),
+ client_secret: z.string().optional(),
code: z.string().min(1, "Missing code"),
redirect_uri: z.string().url({ message: "redirect_uri must be a valid URL" }),
grant_type: z
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index eaa60d2775..f66805eee2 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -414,5 +414,5 @@ model OAuthCode {
expiresAt DateTime
createdAt DateTime @default(now())
- app OAuthApp @relation(fields: [clientId], references: [id], onDelete: Cascade)
+ app OAuthApp @relation(fields: [clientId], references: [clientId], onDelete: Cascade)
}