Skip to content

Commit ecaff08

Browse files
committed
Fix updating a la carte preference in prod: allow auth via bearer token
1 parent 363c40f commit ecaff08

File tree

1 file changed

+40
-9
lines changed
  • web/src/app/api/user/preferences

1 file changed

+40
-9
lines changed

web/src/app/api/user/preferences/route.ts

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,36 @@ import { getServerSession } from 'next-auth'
66
import { z } from 'zod'
77

88
import { authOptions } from '@/app/api/auth/[...nextauth]/auth-options'
9+
import { extractApiKeyFromHeader, getUserIdFromSessionToken } from '@/util/auth'
910
import { logger } from '@/util/logger'
1011

12+
import type { NextRequest } from 'next/server'
13+
1114
const updatePreferencesSchema = z.object({
1215
fallbackToALaCarte: z.boolean().optional(),
1316
})
1417

15-
export async function PATCH(request: Request) {
16-
const session = await getServerSession(authOptions)
18+
export async function PATCH(request: NextRequest) {
19+
let userId: string | undefined
1720

18-
if (!session?.user?.id) {
19-
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
21+
// First, try Bearer token authentication (for CLI clients)
22+
const apiKey = extractApiKeyFromHeader(request)
23+
if (apiKey) {
24+
const userIdFromToken = await getUserIdFromSessionToken(apiKey)
25+
if (userIdFromToken) {
26+
userId = userIdFromToken
27+
}
2028
}
2129

22-
const userId = session.user.id
30+
// Fall back to NextAuth session authentication (for web clients)
31+
if (!userId) {
32+
const session = await getServerSession(authOptions)
33+
userId = session?.user?.id
34+
}
35+
36+
if (!userId) {
37+
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
38+
}
2339

2440
let body: unknown
2541
try {
@@ -68,15 +84,30 @@ export async function PATCH(request: Request) {
6884
}
6985
}
7086

71-
export async function GET() {
72-
const session = await getServerSession(authOptions)
87+
export async function GET(request: NextRequest) {
88+
let userId: string | undefined
89+
90+
// First, try Bearer token authentication (for CLI clients)
91+
const apiKey = extractApiKeyFromHeader(request)
92+
if (apiKey) {
93+
const userIdFromToken = await getUserIdFromSessionToken(apiKey)
94+
if (userIdFromToken) {
95+
userId = userIdFromToken
96+
}
97+
}
98+
99+
// Fall back to NextAuth session authentication (for web clients)
100+
if (!userId) {
101+
const session = await getServerSession(authOptions)
102+
userId = session?.user?.id
103+
}
73104

74-
if (!session?.user?.id) {
105+
if (!userId) {
75106
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
76107
}
77108

78109
const user = await db.query.user.findFirst({
79-
where: eq(schema.user.id, session.user.id),
110+
where: eq(schema.user.id, userId),
80111
columns: { fallback_to_a_la_carte: true },
81112
})
82113

0 commit comments

Comments
 (0)