how to set up automatic login for a user after changing their password using passport-local-mongoose

Trying to automatically log in a user, but encountering an issue with the current 'update' function that looks like this

exports.update = async (req, res) => {
const user = await User.findOne({
    resetPasswordToken: req.params.token,
    resetPasswordExpires: {$gt: Date.now()}
});
if(!user){
    req.flash('error', 'Password reset is invalid or has expired');
    return res.redirect('/login');
}

await user.setPassword(req.body.password);

user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
const updatedUser = await user.save();
await req.login(updatedUser);
req.flash('sucess', "Nice! your password has been reset! You are now logged in!");
res.redirect('/'); 
};

An error is being displayed:

req#login requires a callback function

Error: req#login requires a callback function
at IncomingMessage.req.login.req.logIn (/home/rajat/NOde/myProject-First/node_modules/passport/lib/http/request.js:47:44)
at exports.update (/home/rajat/NOde/myProject-First/controllers/authController.js:94:15)
at processTicksAndRejections (internal/process/task_queues.js:97:5)

The issue appears to be related to await req.login(updatedUser);

Answer №1

Consider using a callback instead of relying solely on async/await

const updatedProfile = await profile.save();
req.logIn(updatedProfile, function(error) {
    if (error) {
        console.log('Failed to log in: ', error);
        return res.redirect('/signin');
    }
    req.flash('success', "Congratulations! Your changes have been saved and you are now logged in!");
    res.redirect('/');
});

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

Am I on the right track in my understanding of how document and viewport relate to mouse position in JavaScript?

After reviewing responses from a previous inquiry, it is evident that both pertain to the x and y coordinates of mouse positions. In relation to the document and In relation to the viewport. I have delved into an article on QuirksMode, yet I feel ther ...

Ensure the video fills the entire width of its parent element and adjusts its height accordingly to maintain a 16:9

I am looking to make both videos fill 100% width of their parent element while keeping their aspect ratio intact. The parent element takes up 50% of the window's width, so the videos need to be responsive. I have come across numerous solutions that ...

Error on the main thread in NativeScript Angular for Android has not been caught

As a beginner in the field of mobile development, I am currently exploring NativeScript and encountering an error in my Android application. https://i.stack.imgur.com/BxLqb.png You can view my package.json here ...

Trouble with reading from a newly generated file in a node.js program

Whenever I launch my results.html page, I generate a new JSON file and use express.static to allow access to the public folder files in the browser. Although my application is functioning properly, I find myself having to click the button multiple times f ...

ng-repeat to display items based on dropdown choice or user's search input

Utilizing $http to retrieve JSON data for display in a table. I have successfully implemented a search functionality where users can search the JSON data from an input field. Additionally, I now want to include a feature that allows users to filter the JSO ...

Shadow and Quality Issues with SVG Images

I have designed a unique SVG image with intricate details and a decorative frame, enhanced with shadowing effects. Unfortunately, after importing this SVG into a react-native application using the react-native-svg library, I noticed that the shadow around ...

Menu changes when hovering

I want to create an effect where hovering over the .hoverarea class will toggle the visibility of .sociallink1, .sociallink2, and so on, with a drover effect. However, my code isn't working as expected. Additionally, an extra margin is automatically ...

UnresolvedPromiseRejectionNotice: MongoDBServerSelectionError: The connection to the 'ip-address' monitor has been terminated. Surprisingly, the code ran smoothly on my colleague's computer

Completely new to this world (less than a month new), my tech lead shared a GitHub repo of an API that I cloned onto my local machine. Following the instructions, I used npm run start in the terminal and received this output: C:\Users\my_path > ...

What is the best way to choose a single li element?

I am working on creating a reservation system using HTML, CSS, and JS. I want to customize the color of the border for each list item (li). However, I want only one li to be selected at a time. When I click on a different li, it should remove the selection ...

How can I create a dropdown menu that is dependent on another dropdown menu using Ajax in my Laravel application?

I have two dropdown fields that are dependent on each other - Class & Section. I am trying to Select * from sections where class_id=selected Class Id. Although I attempted to achieve this using java script, it doesn't seem to work for me. Here are ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...

Supertest and Jest do not allow for sending JSON payloads between requests

Below is the test function I have written: describe("Test to Create a Problem", () => { describe("Create a problem with valid input data", () => { it("Should successfully create a problem", async () => { const ProblemData = { ...

Struggling to resolve the unspecified outcome of an await operation

I'm looking to implement password comparison using the Bcrypt library. Here is the code snippet: bcrypt.js const bcrypt = require('bcrypt'); const saltRounds = 10; var Bcrypt = () => { } Bcrypt.encrypt = async function(password) { ...

Transform the header style columns of react-js Material-tables into rows

Currently experimenting with gradient designs on a material table. While I am able to apply the right color combination to the rows, I seem to be getting column-based results on the title of the table. Attached is a screenshot of my output for reference. ...

Display the input text value when the button is clicked

I am a beginner in JavaScript and have created this HTML page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> Upon entering text into the input field and clicking on the submi ...

Two separate occurrences hold identical values

I'm encountering an issue where instantiating a class two times results in the second instance retaining parameters from the first instance. Here's a simple example: var Test = function() {}; Test.prototype = { bonjour: null, hello: { h ...

Utilize your access token to send a message through Google Business Messages

Currently, I have successfully set up a method to send messages using the Google Business Messages API from an agent to a user through NodeJS. const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); This process requires authenticatio ...

Tips for leveraging stage 3 functionalities in TypeScript?

Array.prototype.at() is currently in the proposal stage 3. Even after adding "lib": ["ESNext"] to my tsconfig.json, I encountered the error: Property 'at' does not exist on type 'number[]'. Could you shed some light ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...

Tips for adjusting the speed of animations in Odometer/vue-odometer

Referencing the Odometer documentation at duration: 3000, // Adjusts the expected duration of the CSS animation in the JavaScript code Even though my code is set up like this, the duration parameter doesn't seem to be effective: <IOdometer a ...