I' new to next.js so trying to do some experiment with next-auth. I was trying to implement custom user email, password which is stored in mongodb and google provider. After several trials, If i login with custom user email and password, I can successfully get authenticated status, but If i try with google provider it will display unauthenticated even after successful login. I can see the list of google account and it redirects me to login page after selection of account. But not sure what is the problem. Can you guys help me with this?
auth.ts
export const authOptions = {
// Configure one or more authentication providers
pages: {
signIn: "/login",
},
adapter: MongoDBAdapter(clientPromise),
secret: process.env.AUTH_SECRET,
debug: process.env.NODE_ENV === "development",
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
}),
// Email & Password
CredentialsProvider({
type: "credentials",
credentials: {
email: {
label: "Email",
type: "text",
},
password: {
label: "Password",
type: "password",
},
},
async authorize(credentials) {
try {
await connectToDb();
// Find user with the email
const user = await User.findOne({
email: credentials?.email,
});
// Email Not found
if (!user) {
throw new Error("Email is not registered");
}
// Check hased password with DB hashed password
const isPasswordCorrect = await bcrypt.compare(
credentials!.password,
user.password
);
// Incorrect password
if (!isPasswordCorrect) {
throw new Error("Password is incorrect");
}
return user;
} catch (err) {
console.log(err);
throw new Error("Failed to login!");
}
},
}),
],
callbacks: {
async signIn({ user, account, profile }: any) {
if (account.provider === "google") {
connectToDb();
try {
const user = await User.findOne({ email: profile.email });
if (!user) {
const newUser = new User({
username: profile?.name,
email: profile.email,
image: profile.picture,
isAdmin: false,
});
await newUser.save();
}
} catch (err) {
console.log(err);
return false;
}
}
return true;
},
},
};
export const getAuthSession = () => getServerSession(authOptions as any);
AuthProvider.tsx
"use client";
import { SessionProvider } from "next-auth/react";
const AuthProvider = ({ children }: { children: React.ReactNode }) => {
return <SessionProvider>{children}</SessionProvider>;
};
export default AuthProvider;