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

Popular posts from this blog

Node JS Express

 Node Js Express npm & Installation npm init npm i express Require // organization of a project const express = require ( "express" ); const compression = require ( "compression" ); const cookieParser = require ( "cookie-parser" ); const csrf = requrie ( "csurf" ); const morgan = require ( "morgan" ); const multer = require ( "multer" ); Initilasation Express const  app = express(); EJS COde app.use( "/static" , path.join(__dirname,  "static" )); app.set( "view engine" ,  "ejs" ); app.set( "views" , path.join(__dirname,  "/views" )); BOdy Post  app.use(express .urlencoded({ extended : true })); Routes  //routers for nav bar ......... app.get( "/" ,(req,res) => {     res.send( "you are at now Home" ) }) app.get( "/about" ,(req,res) => {     res.send( "About Us" ) }) app.get( "/Contect"

JavaScript Hash function

 java Script hash  code for genrating sam number as  function hashCode ( string ) { let hash = 0 ; if (string. length == 0 ) { return hash; } for ( let i = 0 ; i < string. length ; i++) { let char = string. charCodeAt (i); hash = ((hash<< 5 )-hash)+char; hash = hash & hash; } return hash; } let input = document . querySelector ( "#input" ) let output = document . querySelector ( "#output" ) input. addEventListener ( "keyup" , () => { output. value = hashCode (input. value ) }) html < p > Enter text here </ p > < input type = "text" id = "input" > < p > 'Random' number outputted here </ p > < input type = "text" disabled = "disabled" value = "" id = "output" >

Summernote Text Editor

  <! DOCTYPE html > < html >     < head >         < meta charset = "utf-8" >         < meta http-equiv = "X-UA-Compatible" content = "IE=edge" >         < title >compose Blog</ title >         < meta name = "description" content = "" >         < meta name = "viewport" content = "width=device-width, initial-scale=1" >           <!-- CSS only -->         < link rel = "stylesheet" href = "/dashCss/main.css" >         < link rel = "stylesheet" href = "/dashCss/createBlog.css" >           <!-- tailwindcss -->         <!-- <script src="https://cdn.tailwindcss.com"></script> -->           <!-- summarnote cdn -->     < link href = "https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel = "stylesheet" >