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

Aouth #6

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ yarn-error.log*

# local env files
.env*.local
.env

# vercel
.vercel
Expand Down
72 changes: 72 additions & 0 deletions components/Login/Login.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { signIn } from "next-auth/react";
import styles from "./Login.module.scss";
import { useState } from "react";
import { useRouter } from "next/router";

const Login = () => {
const [user, setUser] = useState({
email: "",
password: "",
});
const handleChange = (e) => {
const value = e.target.value;
setUser({
...user,
[e.target.name]: value,
});
};
const router = useRouter();

const handleSubmit = async (e) => {
e.preventDefault();
const { email, password, username } = user;

signIn("credentials", { ...user, redirect: false });
try {
alert("user has been logged in");
router.push("/");
} catch (err) {
alert("An error occuerred" + err);
}
};

const handleGoogleSignIN = async () => {
signIn("google", { callbackUrl: "http://localhost:3000/" });
};
const handleGithubSignIN = async () => {
signIn("github", { callbackUrl: "http://localhost:3000/" });
};

return (
<div className={styles.main}>
<div className={styles.top}>
<h1 className={styles.title}>Login</h1>
</div>
<br />
<div className={styles.sign}>
<form onSubmit={handleSubmit}>
<input
type="email"
placeholder="email"
name="email"
value={user.email}
onChange={handleChange}
/>
<input
type="password"
name="password"
placeholder="password"
value={user.password}
onChange={handleChange}
/>
<button className={styles.form_button}>Sign In</button>
</form>
</div>
<div className={styles.social}>
<button onClick={handleGoogleSignIN}>SignUp with Google</button>
<button onClick={handleGithubSignIN}>SignUp with Github</button>
</div>
</div>
);
};
export default Login;
Empty file.
67 changes: 67 additions & 0 deletions components/Register/Register.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"use client";
import styles from "./Register.module.scss";
import { useState } from "react";
import axios from "axios";
import { useRouter } from "next/router";

const Register = () => {
const [user, setUser] = useState({
name: "",
email: "",
password: "",
});
const router = useRouter();

const handleChange = (e) => {
const value = e.target.value;
setUser({
...user,
[e.target.name]: value,
});
};

const handleSubmit = async (e) => {
e.preventDefault();
axios
.post("/api/register", user)
.then(() => alert("user registered"), router.push("/"))
.catch((err) => alert("An error occured" + err));
};

return (
<div className={styles.main}>
<div className={styles.top}>
<h1 className={styles.title}>Login</h1>
</div>
<br />
<div className={styles.sign}>
<form onSubmit={handleSubmit}>
<input
type="name"
placeholder="name"
name="name"
value={user.name}
onChange={handleChange}
/>
<input
type="email"
placeholder="email"
name="email"
value={user.email}
onChange={handleChange}
/>
<input
type="password"
name="password"
placeholder="password"
value={user.password}
onChange={handleChange}
/>
<button className={styles.form_button}>Register</button>
</form>
</div>
</div>
);
};

export default Register;
Empty file.
4 changes: 4 additions & 0 deletions components/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import Login from "./Login/Login";
import Register from "./Register/Register";

export { Login, Register };
11 changes: 11 additions & 0 deletions context/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"use client";

import { SessionProvider } from "next-auth/react";

export default function Provider({ children }) {
return (
<SessionProvider>
{children}
</SessionProvider>
)
}
3 changes: 3 additions & 0 deletions libs/prismaDB.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient();
export {prisma};
10 changes: 9 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,18 @@
"dependencies": {
"@mdx-js/loader": "^3.0.0",
"@mdx-js/react": "^3.0.0",
"@next-auth/prisma-adapter": "^1.0.7",
"@next/mdx": "^14.1.0",
"@prisma/client": "^5.9.1",
"@types/mdx": "^2.0.11",
"axios": "^1.6.7",
"bcrypt": "^5.1.1",
"default": "link:.prisma\\client\\default",
"next": "14.1.0",
"next-auth": "^4.24.5",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"react-dom": "^18.2.0",
"react-hot-toast": "^2.4.1"
},
"devDependencies": {
"eslint": "^8.56.0",
Expand All @@ -27,6 +34,7 @@
"eslint-plugin-prettier": "^5.1.3",
"lint-staged": "^15.2.2",
"prettier": "^3.2.5",
"prisma": "^5.9.1",
"sass": "^1.70.0",
"simple-git-hooks": "^2.9.0"
},
Expand Down
7 changes: 6 additions & 1 deletion pages/_app.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import '@/styles/globals.scss'
import Provider from '@/context/AuthContext'

export default function App({ Component, pageProps }) {
return <Component {...pageProps} />
return (
<Provider>
<Component {...pageProps} />
</Provider>
)
}
67 changes: 67 additions & 0 deletions pages/api/auth/[...nextauth].jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import NextAuth from "next-auth/next";
import { prisma } from "../../../libs/prismaDB";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
import GithubProvider from "next-auth/providers/github";
import bcrypt from "bcrypt";

export const authOptions = {
adapter: PrismaAdapter(prisma),
providers: [
GithubProvider({
clientId: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
}),
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Email", type: "text", placeholder: "xyx@yahoo.com" },
username: { label: "Username", type: "text", placeholder: "username" },
password: { label: "Password", type: "text", placeholder: "password" },
},
async authorize(credentials) {
if (!credentials.email || !credentials.password) {
throw new Error("Please enter an email and Password");
}
const user = await prisma.user.findUnique({
where: { email: credentials.email },
});

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

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

if (!passwordMatch) {
throw new Error("Incorrect Password");
}
return user;
},
}),
],

callbacks: {
authorized({ req, token }) {
if (token) return true; // If there is a token, the user is authenticated
},
},
secret: process.env.NEXT_AUTH_SECRET,
session: {
strategy: "jwt",
},

debug: process.env.NODE_ENV === "production",
};

const handler = NextAuth(authOptions);

export default handler;
5 changes: 0 additions & 5 deletions pages/api/hello.js

This file was deleted.

41 changes: 41 additions & 0 deletions pages/api/register.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { prisma } from "@/libs/prismaDB";
import bcrypt from "bcrypt";

export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ message: "Method Not Allowed" });
}

const { name, email, password } = req.body;

if (!name || !email || !password) {
return res.status(400).json({ message: "Missing Fields" });
}

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

if (existingUser) {
return res.status(400).json({ message: "Email already exists" });
}

const hashedPassword = await bcrypt.hash(password, 10);

const newUser = await prisma.user.create({
data: {
name,
email,
hashedPassword,
},
});

res
.status(200)
.json({ message: "User registered successfully", user: newUser });
} catch (error) {
console.error("Error registering user:", error);
res.status(500).json({ message: "Internal Server Error" });
}
}
Loading