Skip to main content

authentication with next auth

 making a flolder in api 

like this , api > auth>[...nextauth].js


import NextAuth from "next-auth"

import { verifyPassword } from '../../../lib/auth';
import CredentialsProvider from 'next-auth/providers/credentials';

import clientPromise from "../../../lib/mongodb"
import User from '../../../model/user'

// For more information on each option (and a full list of options) go to
// https://next-auth.js.org/configuration/options
export default NextAuth({
  callbacks: {
    session: async ({ session, token }) => {
      if (session?.user) {
        session.user.id = token.uid;
      }
      return session;
    },
    jwt: async ({ user, token }) => {
      if (user) {
        token.uid = user.id;
      }
      return token;
    },
  },
  session: {
    strategy: 'jwt',
  },
 

  providers: [
    CredentialsProvider({
   
      async authorize(credentials ,req) {
      console.log(credentials)

        const user = await User.findOne({
          email: credentials.email,
        });
       
console.log(user ,'hhjjgbggjhjy')
        if (!user) {
       
          throw new Error('No user found!');
        }
        const isValid = await verifyPassword(
          credentials.password,
          user.password
        );
        if (!isValid) {
          throw new Error('Could not log you in!');
        }
        return user;
      },
    }),
   
  ],

  secret :"thishdwdhwsdwdwdwd3322@@@5s55s5dsddws555d77wsd7w@@Eljkwndw",
  jwt: {
    secret: 'vsvdvsnva3f6s6sw6r3@E$R$Rgdgdfdegdgdsgdxv',
}
});




in API for logging 




import dbConnect from '../../../lib/mongodb'
import User from '../../../model/user.js'
import { hashPassword } from '../../../lib/auth';
import { getSession } from 'next-auth/react';

const  handler = async (req, res)=> {
  const { method } = req
const session = await getSession({req})
  await dbConnect()

  switch (method) {
    case 'GET':
      try {
        if (!session) {
          res.status(401).json('Unauthentication person')
        }
        const users = await User.find({})
        res.status(200).json({ success: true, data: users })
      } catch (error) {
        res.status(400).json({ success: false })
      }
      break
    case 'POST':
      try {
        console.log(req.body)
        const userData = (req.body)
        console.log(userData)
        const {name, email, password } = userData
        if (
          !email ||
          !email.includes('@') ||
          !password ||
          password.trim().length < 7
        ) {
          res.status(422).json({
            message:
              'Invalid input - password should also be at least 7 characters long.',
          });
          return;
        }


        const existingUser = await User.findOne({ email: email });

        if (existingUser) {
          res.status(422).json({ message: 'User exists already!' });
          client.close();
          return;
        }

        const hashedPassword = await hashPassword(password);

        const user = await User.create({
          name: name,
          email: email,
          password: hashedPassword,
  })
        res.status(201).json({ success: true, data: user })
      } catch (error) {
        res.status(400).json({ success: false })
      }
      break
    default:
      res.status(400).json({ success: false })

      case 'PUT':
        try{
          const data = req.body
          console.log(data)
          const user = await User.updateOne({email: data.email},{$set:{name:data.name,email:data.email}})
          console.log(user)
          res.status(200).json({ success: true, data:user })
        }catch (error){
          res.status(400).json({ success: false })
        }
      break
  }
}

export default handler


session provider globel in _app.js


import '../styles/globals.css'
import NavBar  from '../components/navBar'
import Footer from '../components/footer'
import Meta  from '../components/Meta'
import { SessionProvider } from "next-auth/react"

function MyApp({ Component, pageProps:{ session, ...pageProps} }) {
  return (
    <SessionProvider session={session} >
     <Meta/>
    <div className=" container mx-auto font-sans ">
  <NavBar/>
 
  <Component {...pageProps} />
  <Footer/>
</div>
</SessionProvider>
)}

export default MyApp



Comments