Error occurred while looking for user by ID in the everyauth

I previously had a working example with express 2.*, but now I am transitioning to version 3.*. The issue arises during authentication with Facebook, causing some problems. Everything works fine until everyauth makes the GET request to Facebook and then returns an error:

500 Error: WARNING: You are trying to access the attribute/method configured by `findUserById`, which you did not configure. Time to configure it.

Below is the snippet of app.js code:

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , config = require('./conf/config.js')
  , user = require('./routes/user')
  , file = require('./routes/file')
  , http = require('http')
  , path = require('path')
  , everyauth = require('everyauth');

var UserService = require(__dirname + '/db/mongodb/UserService').UserService;

everyauth.facebook
  .appId(config.fb.appId)
  .scope('email')
  .fields('id,name,email')
  .appSecret(config.fb.appSecret)
  .findOrCreateUser(function(session, accessToken, accessToExtra, fbUserMetadata) {
    var promise = this.Promise();
    UserService.findOne({ email: fbUserMetadata.email }, function(err, user) {
      if (!user) {
        // Try to register user
        fbUserMetadata['accessToken'] = accessToken;
        UserService.save(fbUserMetadata);
        user = fbUserMetadata;
      }
      return promise.fulfill(user);
    });
    console.log(fbUserMetadata);
    return promise;
  })
  .findUserById(function(userId, cb) {
    console.log('findByUserId called');
    UserService.findOne({ id: userId }, function(err, user) {
      return cb(err, user);
    });
  })
  .redirectPath('/');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.compress());
  app.use(express.json());
  app.use(express.urlencoded());
  app.use(express.methodOverride());
  app.use(express.cookieParser('your secret here'));
  app.use(express.session());
  app.use(everyauth.middleware(app));
  app.use(app.router);
  app.use(require('less-middleware')({ src: __dirname + '/public' }));
  app.use(express.static(path.join(__dirname, 'public')));
});

everyauth.debug = true;

app.configure('development', function(){
  app.use(express.errorHandler());
});

//console.log(everyauth.facebook);

app.get('/', routes.index);
app.get('/users', user.list);

app.get('/file', file.index);
app.post('/upload', file.upload);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

To resolve this issue, add the following lines:

everyauth.everymodule.findUserById(function(userId, cb) {
    console.log('findByUserId called');
    UserService.findOne({ id: userId }, function(err, user) {
      return cb(err, user);
    });
  });

Answer №1

Try calling the findUserById function on everyauth.everymodule rather than on everyauth.facebook:

everyauth.everymodule.findUserById(function(userId, callback) {
    console.log('findByUserId has been invoked');
    UserService.findOne({ id: userId }, function(error, user) {
        return callback(error, user);
    });
});

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

"Exploring ways to implement validation for multiple email addresses in a textarea using JQuery or JavaScript, while allowing the addresses to be separated by semicol

NOTE: Each email ID must be unique. An empty string value is allowed to be added. Email IDs should be separated by semicolons and commas. Basic validation of email IDs is necessary for entry. [![ $("#d-notification").focusout(function () { var ...

Iframe Loading at Lightning Speed

I have set up a script to load my iframe, but I noticed that the script loads the iframe content too quickly. Is there a way for me to configure it to preload all CSS images and content in the background before showing the full iframe content? Here is my ...

building a REST API with Node.js and Mongoose for handling post, put, and delete requests

I've been diving into creating REST APIs with Node, Mongoose, and Express, and it's been quite a learning experience. While I have a good grasp on how to handle the PUT and DELETE requests, I'm struggling with the POST part of the API. There ...

Are cookie-session and JWT tokens essentially the same thing in Express, or is there a difference between them?

When looking at the express documentation, you will come across a differentiation between express-session and cookie-session. The explanation provided is as follows: There are two main ways to store a user session with cookies: either on the server or on ...

Can loading HTML and js through ajax be considered secure?

I am currently utilizing the Jquery load function $('#result').load('test.php'); in order to dynamically load a page within another page when clicking on a tab. The page being loaded contains javascript, php, and a form. Upon inspecting ...

Node.js: Removing specific _id data from an array

Here is the delete function in my route.js file: router.delete("/qus/:id/answers/:answersId", function(req, res) { Forum.findOneAndUpdate({ _id: req.params.id }, { $pull: { "answers" : { "_id": req.body.answersId } ...

Discover how to use your own search engine suggestions within the search bar of Google Chrome

I recently created a search engine on my website, and everything seems to be working perfectly when I visit the search page. However, I wanted to streamline the process by searching directly from the search box in Chrome. After adjusting the settings to ...

I am unable to deliver an email to the mailbox

Whenever I try to send an email, I encounter an issue. In order to complete the registration process, a confirmation mail needs to be sent. The error message that I receive is: Callback must be a function at maybeCallback const fs = require(& ...

Transforming functions with dependencies into asynchronous operations with the help of promises

Can I convert both of my functions into asynchronous functions, even though one function relies on the other? Is it feasible for function b to execute only after function a? ...

Handle 404 errors using the app.use((err, req, res, next) => {}) function and app.use("*", (err, req, res, next) => {}) method without explicitly setting a 404 return

app.use("/login", login); app.use("*", (err: any, req: Request, res: Response, next: NextFunction) => { console.log('error message') res.send('ERROR 404 Not Found') }); app.use((err: any, req: Request, res: ...

How to enhance a jQuery tab control by implementing custom JavaScript forward and back arrows?

Although there are other questions related to this topic, mine is unique. I have a scrolling jQuery feature that utilizes tabs for selection and is automated. Modifying the layout is challenging because it is dynamic and depends on the number of items in t ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...

Node.js encountering unexpected pattern during RegExp match

Currently, I'm developing a script that aims to simplify local testing by creating a Node server for all my Lambda functions. My main challenge lies in extracting all the dbconfig objects from each file. To test out various patterns, I rely on . Surpr ...

The CORS middleware functions properly with app.get requests, but encounters issues with app.post requests

When utilizing the code snippets below: SERVER: const cors = require('cors') const mongoose = require('mongoose'); const Pet = mongoose.model('pets'); const corsOptions = { origin: 'http://localhost:3000'} app.get ...

Unable to invoke the setState function within the onSubmit handler of Formik

Every time I submit my form, I want to display an alert. I attempted to pass my state as a prop to the component, but it didn't work. Here's how my class state looks: this.state = { alert_variant: '', alert_heading: ...

Incorporating EJS Template Body Parameters into AWS Lambda's Handler.js Using Serverless.yml

I have a scenario where I am trying to embed an EJS template named 'ui.ejs' into my handler.js file. The goal is to extract URL query parameters, then pass them to a function called 'ui.js' to retrieve data, which will then be displayed ...

The Vuex store variable is being accessed prior to being populated with information retrieved from the API

I am currently attempting to retrieve data from an API using Vuex. Below is the action function in the Vuex store: async getEpisodeFromApi({ commit }, id) { const data = { id }; return await axios.get(Api.getUrl(data)).then((res ...

React - error caused by an invalid hook call. Uncaught Error: React encountered a minified error with code #

My goal is to incorporate the micro-frontend concept by implementing various react apps. Container Header Dashboard All three are separate applications. I intend to utilize the Header and Dashboard apps within the Container app. For the Header app, it& ...

What is the solution for the error "does not exist on type 'HTMLTableDataCellElement'" in Angular?

When working on my Angular project, I implemented a PrimeNG p-table component. <p-table [value]="users" class="user-roles-table" [rows]="5" [showCurrentPageReport]="true" [ ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...