Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 2 additions & 46 deletions app/api/auth/[...nextauth]/route.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,3 @@
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import { handlers } from "@auth";

import User from '@models/user';
import { connectToDB } from '@utils/database';

const handler = NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
})
],
callbacks: {
async session({ session }) {
// store the user id from MongoDB to session
const sessionUser = await User.findOne({ email: session.user.email });
session.user.id = sessionUser._id.toString();

return session;
},
async signIn({ account, profile, user, credentials }) {
try {
await connectToDB();

// check if user already exists
const userExists = await User.findOne({ email: profile.email });

// if not, create a new document and save user in MongoDB
if (!userExists) {
await User.create({
email: profile.email,
username: profile.name.replace(" ", "").toLowerCase(),
image: profile.picture,
});
}

return true
} catch (error) {
console.log("Error checking if user exists: ", error.message);
return false
}
},
}
})

export { handler as GET, handler as POST }
export const { GET, POST } = handlers;
49 changes: 49 additions & 0 deletions auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import NextAuth from 'next-auth';
import Google from 'next-auth/providers/google';

import User from '@models/user';
import { connectToDB } from '@utils/database';



export const {auth, handlers} = NextAuth({
providers: [
Google({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
})
],
callbacks: {
async session({ session }) {
// store the user id from MongoDB to session
const sessionUser = await User.findOne({ email: session.user.email });
session.user.id = sessionUser._id.toString();

return session;
},
async signIn({ account, profile, user, credentials }) {
try {
await connectToDB();

// check if user already exists
const userExists = await User.findOne({ email: profile.email });

// if not, create a new document and save user in MongoDB
if (!userExists) {
await User.create({
email: profile.email,
username: profile.name.replace(" ", "").toLowerCase(),
image: profile.picture,
});
}

return true
} catch (error) {
console.log("Error checking if user exists: ", error.message);
return false
}
},
}
})


Loading