vision-agent / auth.ts
MingruiZhang's picture
feat: Setup postgres and prisma (#50)
5ec491a unverified
raw
history blame
No virus
2.22 kB
import NextAuth, { type DefaultSession } from 'next-auth';
import GitHub from 'next-auth/providers/github';
import Google from 'next-auth/providers/google';
import { dbFindOrCreateUser } from './lib/db/functions';
import { redirect } from 'next/navigation';
declare module 'next-auth' {
interface Session {
user: {
/** The user's id. */
id: string;
} & DefaultSession['user'];
}
}
const restrictedPath = ['/project'];
export const {
handlers: { GET, POST },
auth,
} = NextAuth({
providers: [
GitHub,
Google({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_SECRET!,
}),
],
callbacks: {
async signIn({ profile, user }) {
if (!profile) {
return false;
}
const { email, name } = profile;
if (!email || !name) {
return false;
}
const dbUser = await dbFindOrCreateUser(email, name);
if (dbUser) {
user.id = dbUser.id;
return true;
}
return false;
},
async jwt({ token, profile, user }) {
// console.log('[Ming] ~ jwt ~ user:', user, token);
// const dbUser = await dbFindOrCreateUser(email, name);
// console.log('[Ming] ~ signIn ~ dbUser:', dbUser);
if (profile) {
token.id = profile.id || profile.sub;
token.image = profile.avatar_url || profile.picture;
}
return token;
},
session: ({ session, token }) => {
if (token) {
// put db user id into session
session.user.id = token.sub ?? '';
}
return session;
},
authorized({ request, auth }) {
const isAdmin = !!auth?.user?.email?.endsWith('landing.ai');
return restrictedPath.find(path =>
request.nextUrl.pathname.startsWith(path),
)
? isAdmin
: true;
},
},
pages: {
signIn: '/sign-in', // overrides the next-auth default signin page https://authjs.dev/guides/basics/pages
},
});
export async function sessionUser() {
const session = await auth();
const email = session?.user.email;
return {
email,
isAdmin: !!email?.endsWith('landing.ai'),
id: session?.user.id ?? null,
user: session?.user ?? null,
};
}