Untitled
unknown
plain_text
2 years ago
1.6 kB
10
Indexable
import { api } from "@/convex/_generated/api";
import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server";
import { fetchMutation, fetchQuery } from "convex/nextjs";
import { NextResponse } from "next/server";
/**
* Auth create route.
*
* This route is hit when the user login
* without being logged in. It checks if the user is authenticated,
* and if not, redirects them to the login page.
*
* If the user is authenticated, it checks if they have an account
* on our database. If not, it creates one.
*
* Finally, it redirects the user to the dashboard.
*/
export async function GET(request: Request) {
// Get the user from the session
const { getUser } = getKindeServerSession();
const user = await getUser();
// If the user is not authenticated, redirect to login
if (!user)
return NextResponse.redirect(new URL("/api/auth/login", request.url));
try {
// Check if the user has an account on our database
const dbUser = await fetchQuery(api.users.getUser, {
email: user?.email ?? "",
});
// If the user does not have an account, create one
if (!dbUser) {
await fetchMutation(api.users.createUser, {
email: user?.email ?? "",
family_name: user?.family_name ?? "",
given_name: user?.given_name ?? "",
picture: user?.picture ?? "",
});
}
// Redirect the user to the dashboard
return NextResponse.redirect(new URL("/dashboard", request.url));
} catch (error) {
// Log the error
console.log(error);
}
}
Editor is loading...
Leave a Comment