Use CredentialsProvider to enable Next Auth login functionality

I am encountering an issue where I retrieve a user from the database and store it in a variable called result. However, I noticed that the result object does not contain the password key, resulting in the value of result.password being undefined. I am unsure why this is happening and would appreciate any help or insights on this matter. I have seen others on YouTube perform similar actions, but their users do come with the password key.

import CredentialsProvider from "next-auth/providers/credentials"
import dbConnect from '../../../lib/dbConnect';
import User from '../../../models/User';
import { compare } from 'bcryptjs';


export default NextAuth({
    providers: [
        CredentialsProvider({
           name: 'Credentials',
           async authorize(credentials, req) {
               await dbConnect()

               console.log(credentials)

               //check user existence
               const result = await User.findOne({email: credentials.email})

               if(!result){
                   throw new Error('No user Found With Email Please Sign Up!')
               }

               console.log(result) /* the output give me the user back but without the 
                password so result.password is undefind 
                  {
                   _id: new ObjectId("63c6cf0eeed325fcb7d46dbd"),
                   name: 'test user',
                   email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b7aab3bfa2beb792b5bfb3bbbefcb1bdbf">[email protected]</a>',
                   provider: false,
                   isAdmin: false,
                   createdAt: 2023-01-17T16:38:38.133Z,
                   updatedAt: 2023-01-17T16:38:38.133Z,
                   __v: 0
                  }
                 even though i check the database and i found the user there with a 
                 password
                */

               //compare password
               const checkPassword = await compare(credentials.password, result.password)
               if(!checkPassword || result.email !== credentials.email){
                    throw new Error("Email or Password dosen't match")
               }
            return result
          }
        })
      ],
      database: process.env.DB_URL
   })

Answer №1

One problem is that the Mongoose model User has a select: false option set for the password field. This results in the password field being excluded from query results by default. To resolve this, you can include the select option in the findOne method like so:

 const result = await User.findOne({email:credentials.email}).select('+password')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating Scatter Dots into a Horizontal Stacked Bar Chart using Chart.js

My horizontal stacked bar chart is not displaying pink scatter dots based on the right y axis numbers. I need help figuring out what I am doing wrong. When I change the chart to a normal bar instead of horizontal, the dots appear. However, I require them ...

Using ajax for transferring form data to a different php page

Hello everyone, I'm in need of assistance. I have a form on one PHP page and I want to use AJAX to pass the data to another PHP page that will update my database and then return the results. <form name="profile" class="profile"> < ...

I am unable to view the product even though its ID is visible in the URL

import Container from "@/app/components/Container"; import ProductDetails from "./ProductDetails"; import Reviews from "./Reviews"; import { Products } from "@/utilities/Products"; interface Iparams { productid?: ...

The <input> element is not functioning as expected when attempting to use it as a button. I am struggling to find the solution to

My HTML file contains: <!Doctype HTML> <html> <head> <title>Orange’s Game</title> <meta charset="utf-8"> <script src="game.js”></script> </head> <body> <input type="button ...

Create dynamic transitions for hidden elements using a special technique

Is it possible to smoothly transition a div element from display:none to display:block? I attempted to first set the display to block and then apply a transition, but it doesn't seem to be working as expected. HTML <input type="text" class="inp"& ...

Is there a way to load an image asynchronously when the page loads and show a loading gif during the loading process?

My image tag displays a dynamically generated graph from the database. The loading time can vary significantly, sometimes only taking a second while other times it may take up to 6 or 7 seconds for the graph image to appear. I am looking for a way to sho ...

How to Apply a CSS Class to the Body Tag in Angular 2.x

How can I add [class.fixed]="isFixed" to the body tag when Angular 2.x is bootstrapped inside the body (outside my-app)? <html> <head> </head> <body [class.fixed]="isFixed"> <my-app>Loading...</my-app> </body> & ...

Attempting to modify the color of a selected Three.js object causes all objects in the scene to have their colors altered

For example, check out this JSFiddle link. The interesting part occurs during the mousedown event: var hits = raycaster.intersectObjects( [object1, object2, object3] ); if ( hits.length > 0 ) { console.log(hits[ 0 ].object) hits[ 0 ].object.m ...

Is there a way to determine completion of page loading in an AngularJS application using JavaScript?

I am currently in the process of crafting Robot Framework tests to address specific use cases for an external AngularJS application. One of my requirements is the utilization of Python 3.5+ and SeleniumLibrary instead of the outdated Selenium2Library. In ...

Issue with Masonry layout not adjusting to change in window size

Something seems to be fixed on displaying four rows, no matter the size of the window. Previously, it would adjust to three rows or fewer as the browser was resized. I recently played around with columnWidth, but reverting it back to 250 doesn't seem ...

Issue with React Material UI Menu not closing properly

I am struggling to close this menu once it is opened on the page, despite trying various methods like moving the icon button tags around. const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, menuButton: { marginRight: theme.s ...

Steps for extracting a portion of the current page's URL

Can someone help me extract a specific part of the current URL using JavaScript? The URL looks something like this: I need to isolate the number "3153038" from the URL and store it in a JavaScript variable. Thank you! ...

How can I convert Double Quotes from (") to (&quot;) in TinyMce Editor?

While using TinyMce Editor, I have encountered a problem with double quotes breaking my code. In the HTML source of TinyMce, it displays " instead of &quot, causing issues in conversion. It seems that it is not converting " to " as it should, simi ...

Incorporate JSON data into a subsequent AJAX call when coding in JavaScript

I am facing an issue where I need to use data returned from an ajax request to construct a string and then post it back using ajax. However, the variable I'm assigning the data to is not within the scope of the second request, resulting in a 'var ...

Refining the nodes and connections within a directed graph by implementing a filter triggered by clicking a button

I have successfully implemented a force-directed graph. My next step is to incorporate buttons in the main HTML data to enable further filtering. Unfortunately, I haven't been able to make it work yet. I would greatly appreciate any suggestions or gui ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...

jQuery toggle buttons to show or hide on radio button selection

I have a pair of buttons and a pair of radio buttons Buttons 1) btnErp 2) btngoogle Radio Buttons 1) rdiogoogle 2) rdioErp When I select 'rdiogoogle', 'btngoogle' should be visible while 'btnErp' should be hidden. Conve ...

Fixing an erroneous value that has been dragged into the drop function with Jquery

I am encountering an issue with my codes and need some assistance in identifying the problem. The data is being dynamically loaded from the database, and I am using a foreach loop to display all items in a draggable div. The issue arises when I drag an it ...

"Discover the magic of jQuery: Unveiling the hidden div with one simple CSS visibility change

I want to implement a functionality on my screen where the Previous button is hidden initially and only becomes visible when the user clicks the Next button. I have set the CSS property for the Previous button to hide it by default, but despite using an if ...

Incorporating Mongoose Schema structures into my NextJS webpage

I am new to NextJS and seeking assistance with an issue I am facing. I have defined 2 Mongoose schemas and using one on my page without any problems. However, when I try to import the second schema, my page fails to render and throws an error. Regardless ...