Issues with logging out of Facebook using passport

I am currently working on implementing Facebook passport authentication. Below is the code I have in my server.js file for the route used when a user clicks on login via Facebook:

 router.get('/auth/facebook',
      passport.authenticate('facebook',{ scope : 'email' }),
      function(req, res){
      });

Upon successful login, it redirects to success.html which contains a logout button.

 router.get('/auth/facebook/callback',
      passport.authenticate('facebook', {
        successRedirect : '/success',
        failureRedirect: '/'
      }),
      function(req, res) {
        res.render('success.html');
      });

The route for logging out is:

  router.get('/logout', function(req, res){
      req.logout();
      res.redirect('/');
    });

Even when I click on the logout button, I still get redirected to the home page:

router.get('/', function(req, res){
  res.render('auth.html');
});

The content of auth.html is:

<html>
        <head>
          <title>Node.js OAuth</title>
        </head>
        <body>
        <a href="/auth/facebook">Sign in with Facebook</a>
        </body>
        </html>

However, after clicking the "Sign in with Facebook" link, I am directly taken to the success.html page without being able to see the Facebook login page where I would provide credentials. 

I have tried removing details from the database and cookies, as well as using a new browser instance, but I still encounter the same issue. Any guidance on what might be causing this error would be appreciated.

Answer №1

If your page automatically redirects to 'success.html', it's because Facebook has saved your login details. To prevent this, you'll need to manually log out of Facebook from your app.

Here's how you can implement a logout feature for Facebook in your app:

Create a new file named logout.html and add the following code:

<form action="/logoutFromFacebook" method="POST">
  <input type="hidden" name="accessToken" value="<%= user.accessToken %>"/>
</form>

Add the following code to your controller:

router.post('/logoutFromFacebook', function(req, res) {
    res.redirect('https://www.facebook.com/logout.php?next='+server.ip+'/logout&access_token='+req.body['accessToken']);
});

router.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

Note that server.ip should be the URL where your app is hosted. For example, http://localhost:3000 if running locally or if running remotely.

Answer №2

For more information on re-authentication, check out passport-facebook's documentation.

To implement this feature, adjust the initial section as shown below:

router.get('/auth/facebook',
  passport.authenticate('facebook', {
    scope: 'email',
    authType: 'reauthenticate',
    authNonce: 'foo123'
  })
);

Answer №3

remove the facebook access token linked to the particular user account

const apiURL = "https://graph.facebook.com/v15.0/me/permissions?access_token="+accessToken;
     firstValueFrom(
      this.httpService.delete(apiURL).pipe(
        catchError((error: AxiosError) => {
          throw new InternalServerErrorException(error.response);
        }),
      ),
    );

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

Updating fields in a MongoDB collection with identical names

I am seeking guidance on how to update all instances of 'list_price' within a complex collection like this: "cost_price" : 79.9, "list_price" : 189.9, "sale_price" : 189.9, "integrations" : { "erp" : { "mbm" : { "cost_pri ...

Creating PDF files with dynamic image paths retrieved from the database can be easily achieved using various npm packages. Below are the

As I work on building a software using express-mongodb-ejs, I've encountered some challenges with generating and downloading PDFs. While I've explored several npm packages for this purpose, I've found that I am unable to generate a PDF with ...

The scenario of two users simultaneously gaining control access in socket.io creating a race condition

There is a need to ensure that only one user at a time is notified for an available room. I am implementing a solution to prevent multiple users from being notified simultaneously for the same room. socket.on('Check', function (room) { io.in(r ...

Exploring the integration of Stripe Checkout with React and Express.js

Seeking assistance with integrating Stripe Checkout into my React application. I need to create a route in my nodejs/express server that will provide the session id required for setting up Stripe Checkout on the front end. The aim is to redirect users to s ...

Tips for submitting an e-mail through an HTML form with the help of Node.js and Gulp

Today, I've been tackling the challenge of creating an HTML contact form that can send an email using Node.js and Gulp. However, I'm struggling to find a solution. Using a relative path to a simple .PHP file doesn't seem to be working, so it ...

Is it possible to simultaneously update two entities using a single endpoint?

In order to update data in two different entities with a @OneToOne relationship between UserEntity and DetailsEntity, I need to create a function in my service that interacts with the database. Here are the entity definitions: UserEntity @Entity() export ...

I'm looking for a way to fetch data from MySQL using React Native when a button is clicked

I'm encountering an issue with my code when trying to fetch MySQL data by clicking a button. Below is the content of my 'route.js' file: const express = require('express'); const bodyParser = require('body-parser'); ...

Determine the worth of various object attributes and delete them from the list

Currently, my dataset is structured like this: { roof: 'black', door: 'white', windows: 8 }, { roof: 'red', door: 'green', windows: 2 }, { roof: 'black', door: 'green', windows: ...

What is the behavior of a variable when it is assigned an object?

When using the post method, the application retrieves an object from the HTML form as shown below: code : app.post("/foo", (req, res)=> { const data = req.body; const itemId = req.body.id; console.log(data); console.log(itemId); }) ...

Steps to create a private route in Express:

In my current project, I am utilizing a nodejs/express application as the backend solution. This application incorporates passport-jwt to secure specific routes using JWT as the header Authorization. One of these secured routes, known as secure-route, need ...

Ways to update the directory in dotenv using different script commands (listed in package.json) like: launch, check, and more

My issue arises when I need to change the script command in my package.json file from "start" to "test" in order to run Jest tests. This is what my commands look like: "scripts": { "start": "nodemon express/***", "ser ...

I'm curious about the potential vulnerabilities that could arise from using a Secret key as configuration in an express-session

Our code involves passing an object with a secret key's value directly in the following manner --> app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } }) I am pondering wheth ...

Creating dynamic email content with Node.js using SendGrid templating

How can I properly format SendGrid's content using Node.js? I'm currently working on sending emails from a contact form within an application using SendGrid. I have a Google Cloud Function set up that I call via an HTTP post request. Although I ...

Typescript versus ES5: A comparison of Node.js server-side applications written in different languages

Note: When I mention regular JavaScript, I am referring to the ES5 version of JS. As I lay down the groundwork for a new project, my chosen tech stack consists of Node.js for the back-end with Angular2 for the front-end/client-side, and Gulp as the build ...

After logging in successfully, the React app needs a hard refresh to update the

I'm encountering a debugging challenge and would appreciate any assistance from the community. I've been working on my first React app and successfully implemented a Login feature, but after a user logs in, they have to hard refresh their browser ...

generate dynamic custom headers in an express application for accessibility by an Angular application

https://i.stack.imgur.com/6jyNE.pngRecently, I have started using Express and despite my extensive research, I haven't been able to find a solution to my issue. The problem is that I am receiving headers in my Express app, but when I attempt to make t ...

Having issues with installing <package> using npm

I'm currently following a tutorial to install the Angular package in my project. My system already has npm (4.0.5) and node (6.9.2) installed. I navigated to my project folder and executed the following command: npm install angular Despite runnin ...

Which specific file do I need to update for Socket.io configuration when working with Express?

I have organized my app skeleton using express-generator, but I am facing an issue with setting up the socket.io code because my server and routes are in separate files. Most tutorials have everything in one file. The contents of app.js: var routes = req ...

Using socket.io and express for real-time communication with WebSockets

I'm currently working on implementing socket.io with express and I utilized the express generator. However, I am facing an issue where I cannot see any logs in the console. Prior to writing this, I followed the highly upvoted solution provided by G ...

Challenges in MongoDB Aggregation: Overcoming obstacles in combining two collections

I am managing a collection of products and a collection of brands, where each product is associated with a brand. I aim to retrieve each product along with its corresponding brand information. Products Collection: { "_id" : ObjectId("64 ...