-
Notifications
You must be signed in to change notification settings - Fork 153
auth #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
auth #27
Changes from 11 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
e29dd2e
github/vercel integration
ctate a2bbb43
fixes
ctate 47e5282
format
ctate b84871b
fixes
ctate 721094b
format
ctate f50f38c
update readme
ctate 1df5a7d
2.0.0
ctate c37abb1
fix types
ctate 7500d08
fix lint
ctate 5e3fd13
fix build
ctate 995dc48
format
ctate 80f697d
fix issue 1
ctate 146419c
fix issue 2
ctate 7ff92ec
cleanup
ctate afd4acb
fixes
ctate 8666ca1
fix github token
ctate 69a27f9
add upgrade instructions
ctate fb86a0a
update text
ctate 6bff186
fix access
ctate File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
import { NextRequest, NextResponse } from 'next/server' | ||
import { getSessionFromReq } from '@/lib/session/server' | ||
import { db } from '@/lib/db/client' | ||
import { userConnections } from '@/lib/db/schema' | ||
import { eq, and } from 'drizzle-orm' | ||
import { nanoid } from 'nanoid' | ||
import { encrypt, decrypt } from '@/lib/crypto' | ||
|
||
type Provider = 'openai' | 'gemini' | 'cursor' | 'anthropic' | 'aigateway' | ||
|
||
export async function GET(req: NextRequest) { | ||
try { | ||
const session = await getSessionFromReq(req) | ||
|
||
if (!session?.user?.id) { | ||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
} | ||
|
||
const connections = await db | ||
.select({ | ||
provider: userConnections.provider, | ||
createdAt: userConnections.createdAt, | ||
}) | ||
.from(userConnections) | ||
.where( | ||
and( | ||
eq(userConnections.userId, session.user.id), | ||
// Only get API key providers (not OAuth like GitHub) | ||
// Using SQL OR with multiple conditions | ||
eq(userConnections.provider, 'openai'), | ||
), | ||
) | ||
|
||
// Get all API key providers | ||
const allConnections = await db | ||
.select({ | ||
provider: userConnections.provider, | ||
createdAt: userConnections.createdAt, | ||
}) | ||
.from(userConnections) | ||
.where(eq(userConnections.userId, session.user.id)) | ||
|
||
const apiKeyProviders = allConnections.filter((c) => | ||
['openai', 'gemini', 'cursor', 'anthropic', 'aigateway'].includes(c.provider), | ||
) | ||
|
||
return NextResponse.json({ | ||
success: true, | ||
apiKeys: apiKeyProviders, | ||
}) | ||
} catch (error) { | ||
console.error('Error fetching API keys:', error) | ||
return NextResponse.json({ error: 'Failed to fetch API keys' }, { status: 500 }) | ||
} | ||
} | ||
|
||
export async function POST(req: NextRequest) { | ||
try { | ||
const session = await getSessionFromReq(req) | ||
|
||
if (!session?.user?.id) { | ||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
} | ||
|
||
const body = await req.json() | ||
const { provider, apiKey } = body as { provider: Provider; apiKey: string } | ||
|
||
if (!provider || !apiKey) { | ||
return NextResponse.json({ error: 'Provider and API key are required' }, { status: 400 }) | ||
} | ||
|
||
if (!['openai', 'gemini', 'cursor', 'anthropic'].includes(provider)) { | ||
return NextResponse.json({ error: 'Invalid provider' }, { status: 400 }) | ||
} | ||
|
||
// Check if connection already exists | ||
const existing = await db | ||
.select() | ||
.from(userConnections) | ||
.where(and(eq(userConnections.userId, session.user.id), eq(userConnections.provider, provider))) | ||
.limit(1) | ||
|
||
const encryptedKey = encrypt(apiKey) | ||
|
||
if (existing.length > 0) { | ||
// Update existing | ||
await db | ||
.update(userConnections) | ||
.set({ | ||
accessToken: encryptedKey, | ||
updatedAt: new Date(), | ||
}) | ||
.where(and(eq(userConnections.userId, session.user.id), eq(userConnections.provider, provider))) | ||
} else { | ||
// Insert new | ||
await db.insert(userConnections).values({ | ||
id: nanoid(), | ||
userId: session.user.id, | ||
provider, | ||
accessToken: encryptedKey, | ||
}) | ||
} | ||
|
||
return NextResponse.json({ success: true }) | ||
} catch (error) { | ||
console.error('Error saving API key:', error) | ||
return NextResponse.json({ error: 'Failed to save API key' }, { status: 500 }) | ||
} | ||
} | ||
|
||
export async function DELETE(req: NextRequest) { | ||
try { | ||
const session = await getSessionFromReq(req) | ||
|
||
if (!session?.user?.id) { | ||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) | ||
} | ||
|
||
const { searchParams } = new URL(req.url) | ||
const provider = searchParams.get('provider') as Provider | ||
|
||
if (!provider) { | ||
return NextResponse.json({ error: 'Provider is required' }, { status: 400 }) | ||
} | ||
|
||
await db | ||
.delete(userConnections) | ||
.where(and(eq(userConnections.userId, session.user.id), eq(userConnections.provider, provider))) | ||
|
||
return NextResponse.json({ success: true }) | ||
} catch (error) { | ||
console.error('Error deleting API key:', error) | ||
return NextResponse.json({ error: 'Failed to delete API key' }, { status: 500 }) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import { type NextRequest } from 'next/server' | ||
import { OAuth2Client, type OAuth2Tokens } from 'arctic' | ||
import { createSession, saveSession } from '@/lib/session/create' | ||
import { cookies } from 'next/headers' | ||
|
||
export async function GET(req: NextRequest): Promise<Response> { | ||
const code = req.nextUrl.searchParams.get('code') | ||
const state = req.nextUrl.searchParams.get('state') | ||
const cookieStore = await cookies() | ||
const storedState = cookieStore.get(`vercel_oauth_state`)?.value ?? null | ||
const storedVerifier = cookieStore.get(`vercel_oauth_code_verifier`)?.value ?? null | ||
const storedRedirectTo = cookieStore.get(`vercel_oauth_redirect_to`)?.value ?? null | ||
|
||
if ( | ||
code === null || | ||
state === null || | ||
storedState !== state || | ||
storedRedirectTo === null || | ||
storedVerifier === null | ||
) { | ||
return new Response(null, { | ||
status: 400, | ||
}) | ||
} | ||
|
||
const client = new OAuth2Client( | ||
process.env.VERCEL_CLIENT_ID ?? '', | ||
process.env.VERCEL_CLIENT_SECRET ?? '', | ||
`${req.nextUrl.origin}/api/auth/callback/vercel`, | ||
) | ||
|
||
let tokens: OAuth2Tokens | ||
|
||
try { | ||
tokens = await client.validateAuthorizationCode('https://vercel.com/api/login/oauth/token', code, storedVerifier) | ||
} catch (error) { | ||
console.error('Failed to validate authorization code:', error) | ||
return new Response(null, { | ||
status: 400, | ||
}) | ||
} | ||
|
||
const response = new Response(null, { | ||
status: 302, | ||
headers: { | ||
Location: storedRedirectTo, | ||
}, | ||
}) | ||
|
||
const session = await createSession({ | ||
accessToken: tokens.accessToken(), | ||
expiresAt: tokens.accessTokenExpiresAt().getTime(), | ||
}) | ||
|
||
await saveSession(response, session) | ||
|
||
cookieStore.delete(`vercel_oauth_state`) | ||
cookieStore.delete(`vercel_oauth_code_verifier`) | ||
cookieStore.delete(`vercel_oauth_redirect_to`) | ||
|
||
return response | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.