Skip to content

Commit

Permalink
feat: add token API routes for JWT handling (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
Citronnelle committed Jan 14, 2025
1 parent 751c4ab commit 4285398
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
20 changes: 20 additions & 0 deletions app/api/token/refresh.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { signToken } from "@/utils/jwt"
import { verifyToken } from "@/utils/jwt"

/**
* Generate a new JWT based on a valid refresh token.
* @param refreshToken - The provided refresh token.
* @returns A new JWT if the refresh token is valid.
* @throws If the refresh token is invalid or expired.
*/
export function refreshAccessToken(refreshToken: string): string {
try {
// Verify the refresh token
const payload = verifyToken<{ id: string }>(refreshToken)

// Create a new access token
return signToken({ id: payload.id }, "1h") // Set expiration for the new token
} catch (error) {
throw new Error("Invalid or expired refresh token")
}
}
27 changes: 27 additions & 0 deletions app/api/token/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { signToken } from "@/utils/jwt"
import { getSupabaseClient } from "@/utils/supabase/client-provider"
import { NextResponse } from "next/server"

export async function GET(req: Request) {
// Fetch the current user from Supabase (or your auth provider).
const supabase = await getSupabaseClient()
const {
data: { user },
} = await supabase.auth.getUser()

if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}

// Generate an access token.
const accessToken = signToken({
id: user.id,
email: user.email,
role: user.role || "user", // Default to "user" if no role
})

// Optionally, generate a refresh token
const refreshToken = signToken({ id: user.id }, "7d") // Expires in 7 days

return NextResponse.json({ accessToken, refreshToken })
}
22 changes: 22 additions & 0 deletions app/api/token/verify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { verifyToken } from "@/utils/jwt"
import { NextResponse } from "next/server"

export async function POST(req: Request) {
try {
const { token } = await req.json()

if (!token) {
return NextResponse.json({ error: "Token is required" }, { status: 400 })
}

const decoded = verifyToken<{ id: string; email: string; role: string }>(
token,
)
return NextResponse.json({ valid: true, decoded })
} catch (error) {
return NextResponse.json(
{ error: "Invalid or expired token" },
{ status: 401 },
)
}
}

0 comments on commit 4285398

Please sign in to comment.