The issue arises when using multiple route files in Route.js, as it hinders the ability to incorporate additional functions within the

After breaking down Route.js into multiple controllers, I'm stuck on why I can't add an extra function to block permissions for viewing the page.

    // route.js
    module.exports = function(app, passport) {

        app.use('/profile', require('./controllers/profileController'));

    }

.

    // profileController.js
    var express     = require('express')
        , router      = express.Router()
        , permissions = require('../utils/permissions.js')

    // =====================================
    // /profile
    // =====================================
    router.get('/', function(req, res) {
        res.render('Profile/index.ejs', {});
    }

    module.exports = router;

But when I try to implement this in the profileController:

    router.get('/', permissions.isLoggedIn, function(req, res) {
        res.render('Profile/index.ejs', {});
    }

An error is thrown:

    Error: Route.get() requires callback functions but got a [object Undefined]
            at /home/ubuntu/workspace/node_modules/express/lib/router/route.js:171:15
            at Array.forEach (native)
            at Route.(anonymous function) [as get] (/home/ubuntu/workspace/node_modules/express/lib/router/route.js:167:15)
            at Function.proto.(anonymous function) [as get] (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:380:19)
            at Object.<anonymous> (/home/ubuntu/workspace/app/controllers/profileController.js:10:10)
            at Module._compile (module.js:409:26)
            at Object.Module._extensions..js (module.js:416:10)
            at Module.load (module.js:343:32)
            at Function.Module._load (module.js:300:12)
            at Module.require (module.js:353:17)
            at require (internal/module.js:12:17)

Here's some additional information:

    // permissions.js
    var helpers  = require('./helpers.js');

    // route middleware to ensure user is logged in
    function isLoggedInAJAX(req, res, next) {

        // If user is authenticated, proceed
        if (req.isAuthenticated())
            return next();

        res.json(helpers.shootMessage(helpers.getNOK(), "You're not logged in!"));
    }

    // route middleware to ensure user is logged in
    function isLoggedIn(req, res, next) {

        // If user is authenticated, proceed 
        if (req.isAuthenticated())
            return next();

        // Save the current page
        req.session.returnTo = req.path;

        // If not authenticated, redirect to login
        res.redirect('/auth/facebook');
    }

Answer №1

The issue you are facing is due to not properly exporting your functions in the permissions.js file.

// permissions.js
var helpers  = require('./helpers.js');

// Middleware for ensuring a user is logged in during AJAX requests
function isLoggedInAJAX(req, res, next) {

    // Check if the user is authenticated in the session, then proceed 
    if (req.isAuthenticated())
        return next();

    res.json(helpers.shootMessage(helpers.getNOK(), "You're not logged in!"));
}

// Middleware for ensuring a user is logged in
function isLoggedIn(req, res, next) {

    // Check if the user is authenticated in the session, then proceed 
    if (req.isAuthenticated())
        return next();

    // Save the current page
    req.session.returnTo = req.path;

    // If they are not logged in, redirect them to home page
    res.redirect('/auth/facebook');
}

module.exports = {
     isLoggedInAJAX : isLoggedInAJAX,
     isLoggedIn : isLoggedIn
   }

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

In the node/express js environment, the response header is automatically converted to lower case when reading with httpclients like axios and request-promise

When working on my node/express application, I encountered an issue where the response from a third-party server included a custom header key called sessionId, with the 'Id' portion capitalized as per the documentation. However, upon receiving th ...

What is the best way to update a CSS class in React JS?

Suppose I have a CSS class called 'track-your-order' in my stylesheet. Whenever a specific event occurs, I need to modify the properties of this class and apply the updated values to the same div without toggling it. The goal is to replace the ex ...

The date format is malfunctioning -> Error: The date provided is not valid

My goal is to convert the date format from 2022-01-17T21:36:04.000Z to January 18th using the npm package, dateFormat. I found success with the following code snippet: const date = dateFormat("2022-01-17T21:36:04.000Z", "mmmm dS"); However, when trying t ...

Is there a way for me to retrieve props that have been passed through the Vue router within a Vue component?

I have configured a route as shown below: { path: 'fit-details', name: 'fit-details', component: Fitment, props: true }, I am passing props via the route using data from the state: this.$router.push({ path: 'fit-details&a ...

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 ...

React - the state fluctuates

The Goal I'm Striving For: Transmitting data from child to parent. My Approach: Utilizing this.state as outlined here Having trouble summarizing the issue: Upon calling console.log(this.state) in the function where I update the state, the correct va ...

How can I verify if an SVG file has a reliable source? (having troubles converting SVG to canvas)

While attempting to use an SVG generated by a chart plugin (https://wordpress.org/plugins/visualizer/), I am facing issues retrieving the source of the SVG-image being created. Interestingly, when using other SVGs with the same code, everything works perfe ...

Unable to run Node http-server on Ubuntu Linux

I'm attempting to set up a basic http server in my project directory. My goal is to have support for GET requests so that I can retrieve html/css/js files, etc. To achieve this, I decided to utilize the http-server package from npm. After running npm ...

How to make a straightforward task list using ExpressJS

As a beginner, I am attempting to create a basic todo list using ExpressJS. Currently, my goal is to simply display some hardcoded todos that I have in my application. However, I seem to be struggling to identify the mistake in my code. Any assistance woul ...

How can I make arrays of a specific length and populate them in JavaScript?

For instance: I have over 100 locations in a single array, each with latitude and longitude values. I need to use these locations with the Google distance matrix API to find nearby shops for my users. The issue is that this API can only handle 25 destinat ...

Guide to utilizing a JWT token within an httpOnly cookie for accessing a secured API endpoint

Utilizing next.js and next-auth for user login authentication with an API. Once the login is successful, a httpOnly cookie named __Secure-next-auth.session-token is stored in the browser. The following is a sample value (not actual data): eyJhbGciOiJIUzUxM ...

Tips for formatting strings to be compatible with JSON.parse

I'm encountering an issue with my node.js application where I am attempting to parse a string using JSON.parse. Here is the code snippet: try{ skills = JSON.parse(user.skills); }catch(e){ console.log(e); } The string stored in user.skill ...

Is it possible to update labels on an AngularJS slider using a timeout function?

I recently started implementing an AngularJS slider to navigate through various date and time points. Specifically, I am utilizing the draggable range feature demonstrated in this example - https://jsfiddle.net/ValentinH/954eve2L/ The backend provides the ...

The command "node --harmony" cannot be found in this directory

Details: Running Ubuntu 14.04 LTS server --- NodeJS version 5.7.0 --- NPM version 3.6.0 I have developed a custom command-line tool with the initial command: #!/usr/bin/env node --harmony. It works perfectly fine on my local machine which also has NodeJS ...

Issue encountered when attempting to assign an action() to each individual component

I'm facing an issue with the button component I've created. import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-button', template: ` <ion-button color="{{color}}" (click)="action()"&g ...

formik does not support using the "new Date" function as an initial value

I have been trying to set the initial value of a date in my component like this, but when it renders I am encountering an error. const formik = useFormik ({ initialValues: { dob: new Date () } }) During this process, I'm facing the follow ...

What is the best way to instruct Ajax to choose the specific item clicked within a list?

I am currently working on creating a list of people on vacation and I want to calculate their return date when the "Return Date" link is clicked. I have been able to achieve this, however, whenever I click any of the buttons in the list, it always passes t ...

What is the best way to focus the video on its center while simultaneously cropping the edges to keep it in its original position and size?

I'm trying to create a special design element: a muted video that zooms in when the mouse hovers over it, but remains the same size as it is clipped at the edges. It would be even more impressive if the video could zoom in towards the point where the ...

Can an ejs template be displayed without the need to refresh the page?

I'm currently developing a game server that involves players entering a game room and getting paired with another player. One feature I would like to implement is displaying the game board without having to reload the page in order to avoid reinitiali ...

Exploring an Array Based on User's Input with JavaScript

Looking to implement a search functionality for an array using AJAX. The array is pre-populated with values, and the user will input a value in a HTML text box. If the entered value is found in the array, it should display "Value found", otherwise "not f ...