Save user to database
This commit is contained in:
+24
-5
@@ -1,3 +1,6 @@
|
|||||||
|
import connectDB from '@/config/database';
|
||||||
|
import User from '@/models/User';
|
||||||
|
|
||||||
import GoogleProvider from 'next-auth/providers/google';
|
import GoogleProvider from 'next-auth/providers/google';
|
||||||
|
|
||||||
export const authOptions = {
|
export const authOptions = {
|
||||||
@@ -18,15 +21,31 @@ export const authOptions = {
|
|||||||
// Invoked on successful signin
|
// Invoked on successful signin
|
||||||
async signIn({ profile }) {
|
async signIn({ profile }) {
|
||||||
// 1. Connect to database
|
// 1. Connect to database
|
||||||
// 2. Check if user exists in database
|
await connectDB();
|
||||||
// 3. If not, create user in database
|
// 2. Check if user exists
|
||||||
// 4. return true to allow sign in
|
const userExists = await User.findOne({ email: profile.email });
|
||||||
|
// 3. If not, then add user to database
|
||||||
|
if (!userExists) {
|
||||||
|
// Truncate user name if too long
|
||||||
|
const username = profile.name.slice(0, 20);
|
||||||
|
|
||||||
|
await User.create({
|
||||||
|
email: profile.email,
|
||||||
|
username,
|
||||||
|
image: profile.picture,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// 4. Return true to allow sign in
|
||||||
|
return true;
|
||||||
},
|
},
|
||||||
// Session callback function that modifies the session object
|
// Modifies the session object
|
||||||
async session({ session }) {
|
async session({ session }) {
|
||||||
// 1. Get user from database
|
// 1. Get user from database
|
||||||
// 2. Assign user id from database to session
|
const user = await User.findOne({ email: session.user.email });
|
||||||
|
// 2. Assign the user id to the session
|
||||||
|
session.user.id = user._id.toString();
|
||||||
// 3. return session
|
// 3. return session
|
||||||
|
return session;
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user