Steps to enable multiple users to log in through a single route

I've developed a login code for managing two different schemas - User and Admin. Currently, I have separate login routes: /login for normal users and super admins, and /adminLogin for admin users and super admins.

My goal is to merge these two schemas into a single route /login.

Below is the code snippet for the /login route, which is similar to /adminLogin, with the main difference being the use of the User and Admin schemas:

router.post('/login' , (req, res, next) => {

    User.find({email: req.body.email})
    .exec()
    .then(user => {
        if(user.length < 1) {
            return res.status(401).json({
                message: "Authentication failed. User not found."
            })
        }
        bcrypt.compare(req.body.password, user[0].password, (err, result) =>{
        if (err) {
        return res.json({
                message: "Authentication failed. Check email and password"
                });             
            }


            if (result && user[0].isVerified === true){
                const adminEmail = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="770f0e0d3703121a075a1a161e1b5914181a">[email protected]</a>";                                                 
                const role = user[0].email===adminEmail? "superadmin" : "user";     //---- Here in case of Admin schema -> "superadmin" : "admin";
                const token = jwt.sign( 
                    {
                        email: user[0].email,
                        userId: user[0]._id,
                        phoneNo: user[0].phoneNumber,
                        role            
                    },
                    process.env.JWT_KEY,
                    {
                        expiresIn : "1h"
                    });
                    return res.status(200).json({
                    message: "Authentication Successful",
                    token : token
                    });
            }
            else{
                console.log("user is not verified");    
                return res.json({
                message: "User is not verified"
                }); 
            }

My question is how can I incorporate Admin.find() for the Admin schema within the same login function?

Answer №1

Utilizing query parameters allows for the transmission of user type data, which can then be accessed within the controller function through the req.query object.

Answer №2

To optimize your code without altering the schema, you can start by refactoring it in the following way:

function handle(find_func, base_role, req, res, next) {
     find_func( // Replace "superadmin" : "user" with "superadmin" : base_role in your original code inside User.find
     ...);
}

For a regular user login, use the following:

handle(User.find, "user", req, res, next);

For an admin user login, use the following:

handle(Admin.find, "admin", req, res, next);

Now you must differentiate between a login from a regular user and an admin user. Instead of merging your admin and user schemas into one larger schema with a new field "role" indicating the type of user, you can check if the username exists in the User collection first and if not, check in the Admin collection, then call the corresponding handle function.

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

Guide on Adding a Map to a List in JavaScript

Currently, I am trying to extract data from a form and add it as a map to my list. However, an error message is displayed: Cannot read property 'url' of undefined express = require("express"); app = express(); var bodyParser = require("body- ...

Node.js maintains a duplicate of a global variable within the local scope

I am facing a challenge with my Node.js application that utilizes the request library to retrieve multiple URLs. The code structure looks similar to this: for(var i = 0; i < docs.length; i++){ var URL = docs[i].url; request(URL, functi ...

Establish a global variable within the utils.js module in a Node.js environment

Hey there, I'm currently in the process of trying to figure out how to properly define a global variable in node.js. I am aware that it's not considered best practice, but in this specific scenario, it seems like the only way to go without involv ...

Create a new Error stating that the PFX file or certificate with the private key is not found

I recently created a node.js module, tested it thoroughly, and uploaded it to Github. I then downloaded the zipped version of the module from Github, installed all dependencies, and attempted to run it. However, I encountered this error: Error: Missing PF ...

Guide on routing error 500 globally to a specific page with React-Redux

Currently, I am utilizing the react-redux starter found at this link. I am seeking guidance on how to redirect all API 500 errors to a specific page. Can someone assist me with this? ...

Unveiling the steps to automatically conceal a submitted form in React, no longer requiring the manual activation of a toggle button

Currently, I have a list of songs and a toggle button that reveals a form to add a new song. However, I want the form to hide automatically after submission without requiring another button click. I tried using useEffect but couldn't get it to work. A ...

Issues with triggering the success block in AngularJS and Node.js Express when using $http.get

As a beginner in the world of AngularJS and Node.js, I'm facing an issue with my $http.get method. The problem is that the success callback block does not get executed when the request is successful, whereas the error callback works just fine when the ...

Guide on inserting a date into a MySQL DATETIME column in Angular with Node.js

In my application, I have a date picker component. My goal is to store the selected date in a MySQL database column with the data type of DATETIME. When using Angular, the value retrieved from the date picker is displayed as such: console.log(date.value): ...

Is NoSQL supported by the MySQL Community Edition?

I have decided to dive into learning and developing a Node.js application with SQL. I am aware that the MySQL Enterprise Edition offers support for NoSQL, but I'm curious if the community edition also supports NoSQL or if I need to invest in the enter ...

Adjust image size using Node.js and ImageMagick

How can I resize images before sending them to users in Node.js using Express? im = require("imagemagick") app.get('/image/:dossier/:id/:taille', function (req, res) { var image = __dirname + '/public/img/bibliotheque/'+req.params ...

unable to access app.local in a routing file

So, in my express.js 4.13.3, I have set a variable called app.local in the app.js file. app.set('multimedia', __dirname + '/public/multimedia'); Now, in the routes/settings.js, I'm trying to access that variable like this: var a ...

Invalidating the express response object due to a TypeError issue

Currently, I am in the process of writing a test that utilizes sinon and sinon-express-mock to mock an incorrect request. The goal is to then call a validation function within my application and verify that it returns the expected response status code (400 ...

Transitioning from Jade (PUG) to Handlebars: Solving the Problem with Loading SVG Images using Helper Functions

I have a project originally written in Pug that I am now converting to Handlebars. The issue I am encountering is that instead of loading the image, it displays markup text. This was not a problem when using Pug (Jade). To address this, I created a helpe ...

Encountered error code 3228369023 while trying to establish a connection to a SQL Server database using Node.js with MSSQL

Currently in the process of setting up an API for a SQL Server Express database, my plan is to utilize mssql in Node.js with express to handle requests and communicate with the database. Despite trying several methods to establish a connection between my n ...

Is there an alternative to @bittrance/azure-function-express that supports the newest node versions?

I recently utilized the azure-function-express package, specifically the @bittrance/azure-function-express version, to establish a connection between an Express application and an Azure Function handler. This allowed for seamless integration of all familia ...

Gulp is unable to successfully make an API post request

I am facing an issue where a specific request is not successful. Although I receive a response, it is not the desired success response. The request works fine when sent from Postman, but encounters problems when executed in Gulp. var proj = { "APIKey" ...

Error encountered during Stenciljs project setup

I am attempting to start a fresh stenciljs project by using the command npm init stencil Upon executing the above command, I encounter this error https://i.stack.imgur.com/L7ke4.png Could someone kindly assist me in identifying what is causing the issue. ...

Exploring the world of promise testing with Jasmine Node for Javascript

I am exploring promises testing with jasmine node. Despite my test running, it indicates that there are no assertions. I have included my code below - can anyone spot the issue? The 'then' part of the code is functioning correctly, as evidenced b ...

I'm having trouble adding headers to my axios post request. The post route functions correctly in Postman but does not work when using axios. Can anyone

Implementing JWT for protecting a post route in my nodejs, express, react application has been quite a challenge. While testing with postman and adding the JWT token to the headers works flawlessly to add users to the database, I encounter a 401 response ( ...

Mongoose aggregate not returning any results

I'm currently working on using Mongoose aggregate to group businesses. I have a MongoDB script that is functioning properly. Below, you'll find the NodeJS code with Mongoose as well as the MongoDB code: History.aggregate() .cursor({ bat ...