From 716053d09c3e1bd5a4bbd95afe8f0d1544485573 Mon Sep 17 00:00:00 2001 From: Sid-80 Date: Fri, 26 Jul 2024 19:06:11 +0530 Subject: [PATCH] feat: signin with google --- src/app/api/auth/[...nextauth]/options.ts | 79 ++++++++++++++++------- src/app/dashboard/layout.tsx | 2 + src/app/signin/page.tsx | 2 + src/components/shared/SigninForm.tsx | 13 ++-- src/components/shared/SignupForm.tsx | 7 -- 5 files changed, 65 insertions(+), 38 deletions(-) diff --git a/src/app/api/auth/[...nextauth]/options.ts b/src/app/api/auth/[...nextauth]/options.ts index 3f3eefd..0d6a2e6 100644 --- a/src/app/api/auth/[...nextauth]/options.ts +++ b/src/app/api/auth/[...nextauth]/options.ts @@ -3,6 +3,7 @@ import CredentialsProvider from "next-auth/providers/credentials"; import UserModel from "@/models/user"; import bcrypt from "bcryptjs"; import { mongoDB } from "@/lib/MongoDB"; +import GoogleProvider from "next-auth/providers/google"; export const options: NextAuthOptions = { providers: [ @@ -26,7 +27,7 @@ export const options: NextAuthOptions = { try { await mongoDB(); const user = await UserModel.findOne({ email }); - console.log(user) + if (!user) { throw new Error("Not Registered!"); } @@ -36,19 +37,23 @@ export const options: NextAuthOptions = { return user; } catch (e) { - console.log(e) + console.log(e); } }, }), + GoogleProvider({ + clientId: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID!, + clientSecret: process.env.NEXT_PUBLIC_GOOGLE_SECRET_ID!, + }), ], - session:{ - strategy:"jwt", + session: { + strategy: "jwt", }, pages: { signIn: "/signin", }, secret: process.env.NEXTAUTH_SECRET, - callbacks:{ + callbacks: { async session({ session, token }) { session.user = { ...session.user, @@ -62,27 +67,55 @@ export const options: NextAuthOptions = { }; return session; }, - async jwt({ token, user }:any) { - if (user) { - // Generate access and refresh tokens when the user is defined - const accessToken = user.generateAccessToken(); - const refreshToken = user.generateRefreshToken(); + async jwt({ token, user, account }: any) { + try { + if (user) { + // Generate access and refresh tokens when the user is defined + const accessToken = user.generateAccessToken(); + const refreshToken = user.generateRefreshToken(); + + // Save the refresh token to the user document + user.refreshToken = refreshToken; + await user.save({ validateBeforeSave: false }); + + token.id = user._id; + token.email = user.email; + token.firstName = user.firstName; + token.lastName = user.lastName; + + token.accessToken = accessToken; + token.refreshToken = refreshToken; + + token.image = user.image; + } else{ + // User authenticated with Google, generate tokens here + const existingUser = await UserModel.findOne({ email: token.email }); + if (existingUser) { + const accessToken = existingUser.generateAccessToken(); + const refreshToken = existingUser.generateRefreshToken(); - // Save the refresh token to the user document - user.refreshToken = refreshToken; - await user.save({ validateBeforeSave: false }); - - token.id = user._id; - token.email = user.email; - token.firstName = user.firstName; - token.lastName = user.lastName; - - token.accessToken = accessToken; - token.refreshToken = refreshToken; + existingUser.refreshToken = refreshToken; + await existingUser.save({ validateBeforeSave: false }); - token.image = user.image + token.id = existingUser._id; + token.email = existingUser.email; + token.firstName = existingUser.firstName; + token.lastName = existingUser.lastName; + + token.accessToken = accessToken; + token.refreshToken = refreshToken; + + token.image = existingUser.image; + } + if (!existingUser) { + throw new Error("Not Registered!"); + } + + } + } catch (err) { + console.log(err); } return token; - } + }, }, }; diff --git a/src/app/dashboard/layout.tsx b/src/app/dashboard/layout.tsx index 77cd68f..e0f0622 100644 --- a/src/app/dashboard/layout.tsx +++ b/src/app/dashboard/layout.tsx @@ -36,6 +36,8 @@ function DashboardLayout({ const dispatch = useDispatch(); const axiosInstance = createAxiosInstance(user.accessToken); + console.log(session) + useEffect(() => { if (session && !hasCheckedTeam) { checkTeam(); diff --git a/src/app/signin/page.tsx b/src/app/signin/page.tsx index a17628c..0b2e424 100644 --- a/src/app/signin/page.tsx +++ b/src/app/signin/page.tsx @@ -14,6 +14,8 @@ export default function Page() { const { data: session,status } = useSession(); const dispatch = useDispatch(); + console.log(session) + useEffect(() => { if (session) { dispatch( diff --git a/src/components/shared/SigninForm.tsx b/src/components/shared/SigninForm.tsx index 0156eec..43e9137 100644 --- a/src/components/shared/SigninForm.tsx +++ b/src/components/shared/SigninForm.tsx @@ -16,12 +16,13 @@ import { LogInIcon } from "lucide-react"; import Link from "next/link"; import { Separator } from "../ui/separator"; import Image from "next/image"; -import { signIn } from "next-auth/react"; +import { signIn, signOut } from "next-auth/react"; import { useRouter } from "next/navigation"; import { useDispatch } from "react-redux"; import { useSelector } from "react-redux"; import { RootState } from "@/config/store"; import { toast } from "sonner"; +import { logOut } from "@/app/Redux/Auth/auth-slice"; const FormSchema = z.object({ email: z.string().email().min(1, { @@ -43,12 +44,6 @@ export function SigninForm({session}: Props) { router.push('/dashboard'); } - // const isAuth = useSelector((state:RootState)=>state.auth.user?.isAuth); - - // if(isAuth){ - // router.push('/dashboard'); - // } - const form = useForm>({ resolver: zodResolver(FormSchema), defaultValues: { @@ -132,7 +127,9 @@ export function SigninForm({session}: Props) {
- diff --git a/src/components/shared/SignupForm.tsx b/src/components/shared/SignupForm.tsx index 2aa4efb..ac6bf45 100644 --- a/src/components/shared/SignupForm.tsx +++ b/src/components/shared/SignupForm.tsx @@ -165,13 +165,6 @@ export function SignupForm({session}: Props) { -
- -
-

Already have an account?{" "}