Skip to content

Commit

Permalink
Implemented next-auth with credentials and created current-user api
Browse files Browse the repository at this point in the history
  • Loading branch information
PrathmeshSadake committed Jun 5, 2023
1 parent 37887a2 commit 9340edf
Show file tree
Hide file tree
Showing 7 changed files with 156 additions and 0 deletions.
16 changes: 16 additions & 0 deletions hooks/useCurrentUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import useSWR from "swr";

import fetcher from "@/libs/fetcher";

const useCurrentUser = () => {
const { data, error, isLoading, mutate } = useSWR("/api/current", fetcher);

return {
data,
error,
isLoading,
mutate,
};
};

export default useCurrentUser;
5 changes: 5 additions & 0 deletions libs/fetcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import axios from "axios";

const fetcher = (url: string) => axios.get(url).then((res) => res.data);

export default fetcher;
13 changes: 13 additions & 0 deletions libs/prismadb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { PrismaClient } from "@prisma/client";

const globalForPrisma = global as unknown as {
prisma: PrismaClient | undefined;
};

export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: ["query"],
});

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
26 changes: 26 additions & 0 deletions libs/serverAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth";
import { prisma } from "./prismadb";

const serverAuth = async (req: NextApiRequest, res: NextApiResponse) => {
const session = await getServerSession(req, res, authOptions);

if (!session?.user?.email) {
throw new Error("Not signed in");
}

const currentUser = await prisma.user.findUnique({
where: {
email: session.user.email,
},
});

if (!currentUser) {
throw new Error("Not signed in");
}

return { currentUser };
};

export default serverAuth;
54 changes: 54 additions & 0 deletions pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import bcrypt from "bcrypt";
import NextAuth, { AuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/libs/prismadb";

export const authOptions: AuthOptions = {
adapter: PrismaAdapter(prisma) as any,
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "email", type: "text" },
password: { label: "password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
throw new Error("Invalid credentials");
}

const user = await prisma.user.findUnique({
where: {
email: credentials.email,
},
});

if (!user || !user?.hashedPassword) {
throw new Error("Invalid credentials");
}

const isCorrectPassword = await bcrypt.compare(
credentials.password,
user.hashedPassword
);

if (!isCorrectPassword) {
throw new Error("Invalid credentials");
}

return user;
},
}),
],
debug: process.env.NODE_ENV === "development",
session: {
strategy: "jwt",
},
jwt: {
secret: process.env.NEXTAUTH_JWT_SECRET,
},
secret: process.env.NEXTAUTH_SECRET,
};

export default NextAuth(authOptions);
18 changes: 18 additions & 0 deletions pages/api/current.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import serverAuth from "@/libs/serverAuth";
import { NextApiRequest, NextApiResponse } from "next";

export default async function handle(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== "GET") {
return res.status(405).end();
}
try {
const { currentUser } = await serverAuth(req, res);
return res.status(200).json(currentUser);
} catch (error) {
console.log(error);
return res.status(400).end();
}
}
24 changes: 24 additions & 0 deletions pages/api/register.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { prisma } from "@/libs/prismadb";
import bcrypt from "bcrypt";
import { NextApiRequest, NextApiResponse } from "next";

export default async function handle(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== "POST") {
return res.status(405).end();
}

try {
const { email, username, name, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 12);
const user = await prisma.user.create({
data: { email, username, name, hashedPassword },
});
res.status(200).json(user);
} catch (error) {
console.log(error);
return res.status(400).end();
}
}

0 comments on commit 9340edf

Please sign in to comment.