Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: signin with google #492

Merged
merged 1 commit into from
Jul 26, 2024
Merged
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
79 changes: 56 additions & 23 deletions src/app/api/auth/[...nextauth]/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand All @@ -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!");
}
Expand All @@ -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,
Expand All @@ -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;
}
},
},
};
2 changes: 2 additions & 0 deletions src/app/dashboard/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ function DashboardLayout({
const dispatch = useDispatch();
const axiosInstance = createAxiosInstance(user.accessToken);

console.log(session)

useEffect(() => {
if (session && !hasCheckedTeam) {
checkTeam();
Expand Down
2 changes: 2 additions & 0 deletions src/app/signin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export default function Page() {
const { data: session,status } = useSession();
const dispatch = useDispatch();

console.log(session)

useEffect(() => {
if (session) {
dispatch(
Expand Down
13 changes: 5 additions & 8 deletions src/components/shared/SigninForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand All @@ -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<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
Expand Down Expand Up @@ -132,7 +127,9 @@ export function SigninForm({session}: Props) {
<Separator className="w-full" />

<div className="flex items-center justify-center">
<Button className="flex gap-2" variant={"secondary"}>
<Button type="button" onClick={() => {
signIn('google')
}} className="flex gap-2" variant={"secondary"}>
Sign-in with Google{" "}
<Image src={"/google.svg"} alt="google" width={18} height={18} />
</Button>
Expand Down
7 changes: 0 additions & 7 deletions src/components/shared/SignupForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,13 +165,6 @@ export function SignupForm({session}: Props) {

<Separator className="w-full" />

<div className="flex items-center justify-center">
<Button className="flex gap-2" variant={"secondary"}>
Sign-in with Google{" "}
<Image src={"/google.svg"} alt="google" width={18} height={18} />
</Button>
</div>

<p className=" text-xs text-center text-gray-400">
Already have an account?{" "}
<Link href={`/signin`} className=" underline">
Expand Down
Loading