Is it feasible to utilize the local strategy in PassportJS without a database?

I am currently working on a small NodeJS server that connects to ElasticSearch. However, I am facing the challenge of implementing user authentication as storing user information in ElasticSearch is not an ideal solution.

Instead of adding complexity by using MongoDB for storing user accounts, I am exploring the option of utilizing PassportJS local strategy with either a json file containing user accounts or keeping an array of user accounts in memory.

Since users will be provisioned manually and there will only be a few users, manually editing a json file seems like a feasible solution.

UPDATE: If possible, could you provide me with an example of how to implement this?

Thank you

Answer №1

If you're looking to delve deeper into PassportJS authentication, check out this insightful blog post: Passport authentication. I've included additional comments where necessary. All you have to do is tweak the code from fetching user data from a database to pulling it from a JSON file.

// config/passport.js

// necessary modules
var LocalStrategy   = require('passport-local').Strategy;

// importing users' JSON data
var User            = require('../app/data/users');

// export the module function for app use
module.exports = function(passport) {

    // =========================================================================
    // passport session setup ==================================================
    // =========================================================================
    // required for persistent login sessions
    // needed for serializing and deserializing users in/out of session

    // serialize user for the session
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // deserialize the user
    passport.deserializeUser(function(id, done) {
        // Implement logic to retrieve user from json data using userID


        // Return done({}) if not found

        // Otherwise, return done(null, userObject);
    });

    // =========================================================================
    // using named strategies for login and signup
    // defaults to 'local' if no specified name

    passport.use('local-login', new LocalStrategy({
        // override default username and password with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // pass entire request back to callback
    },
    
    function(req, email, password, done) { // callback with form email and password

        // Find user in json data based on email
        
        // Validate password
        
        
        // If user not found or incorrect password, return done({})
        
        // Else return done(null, userObject);
    }));

};

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

I encountered a CORS policy error while using React. What steps can I take to effectively manage and resolve this

INDEX.JS import express from "express"; import { APP_PORT } from "./config"; import db from "./database"; import cors from "cors"; import bodyParser from "body-parser"; import Routes from "./routes&quo ...

Managing access control permissions in Node.js using the Express framework

I am currently developing a node.js application using the express framework. My goal is to implement ACL permissions within this node.js and express setup. I have been experimenting with the acl package. In my server.js file, I have the following code: ...

"Understanding How to Utilize the Grpc Stream Variable for Extended Processes in Node.js

Utilizing Node.js for connecting to a server through gRPC in order to execute a lengthy task. The server sends a one-way stream to the client (Node.js app) while the task is ongoing. I am looking to add a Stop button and have been advised that closing the ...

Encountering the SequelizeConnectionRefusedError while using docker in conjunction with sequelize

My Docker configuration is set up as follows: web: image: ca9a385372b0 volumes: - .:/src ports: - "8000:8000" container_name: web links: - mysql mysql: image: 7666f75adb6b environment: container_name: mysql ports: - "6603: ...

Create PDFs using PhantomJS when the HTML content is fully loaded and ready

I am a newcomer to utilizing phantomjs and encountering difficulties in rendering my website as a PDF file. Although I can successfully render a simple version of the page, issues arise when multiple images and web fonts are involved, causing the DOM not t ...

Even after installing npm3, the npm -v command continues to display version 2.x.x

As I delve into the world of Angular 2, I learned that it requires npm version 3.x.x. Despite installing npm3 with the command npm install -g npm3, when I check my npm version using npm -v, it still shows as 2.15.8. Strangely, running npm3 -v displays vers ...

Managing multiple client requests at the same time with Node and Express

I am faced with the challenge of handling multiple user requests simultaneously in my express server and storing their data in a MongoDB. While I have all the necessary code prepared, I am struggling to devise a method for assigning a unique identifier to ...

The content located at “http://localhost:3000/public/static/” was restricted because of a mismatch in MIME type (text/html) which triggered the X-Content-Type-Options:nosniff protocol

https://i.stack.imgur.com/7Etn7.png Every time I try to run the server with nodemon, I keep encountering the error mentioned in the title. Below is the code snippet from the JavaScript file: const express = require('express') const path = requir ...

NodeJS Throws an Error: Unexpected Symbol

Looking to create a website based on Rullete. I have the necessary code and scripts, but when I try to run the script, I encounter an error. [SyntaxError: Unexpected token <] SyntaxError: Unexpected token < at Object.parse (native) at Reques ...

Encountering a "Connection Refused" error when attempting to test a React and Express application

Currently, I am developing an order system using React for the frontend (port 3000) and Express for the backend (port 3001). Everything functions perfectly when tested on the same MacBook that hosts the node project. However, when testing it on a differen ...

The compilation of PKG using Axios 1.x encounters an error

Despite attempting numerous strategies, I have not been successful. I developed a Node.js application with API requests managed using axios. However, I am unable to convert it into an executable file. Trying to downgrade Axios to version 0.27.0 resolved th ...

Is it possible to determine the file size of an http-streamed file?

In my node app, I am sending a large file via express using a stream since the size of the file is substantial. When the receiving node app downloads the file, I want to be able to monitor the progress of the download. I came across a discussion on Stack ...

`How to handle prompts from OpenSSL in a Node.js environment`

I need help removing a password from a private key file by using openssl with node js. This is the code in node js: cmd = exec('/usr/bin/openssl', [ 'rsa', '-in', `${process.cwd()}/privkey.pem`, '-out', ...

Guidelines for Nestjs class-validator exception - implementing metadata information for @IsNotIn validator error handling

I have a NestJs data transfer object (dto) structured like this import { IsEmail, IsNotEmpty, IsNotIn } from 'class-validator'; import { AppService } from './app.service'; const restrictedNames = ['Name Inc', 'Acme Inc&ap ...

React Dependency Conflict: Material-UI (Mui) Causing Issues of Incompatibility

While trying to install react dependencies using npm i in Netlify, it appears that there are some missing or unresolved libraries in material-ui. Could someone offer assistance in determining the correct versions? 1:48:24 PM: Failed during stage "Ins ...

Storing tasks in the server backend for later access

Struggling to find the most efficient way to store todo list items in the backend. I've heard that storing arrays and objects directly in the backend may not be optimal. Currently working on a web app inspired by Google Keep. Here's some context ...

Is it necessary to use asynchronous actions in Node.js only when developing server applications?

In the Node.js application I'm developing, there is a piece of code similar to this within an async function: await a(param1); await b(param2); await c(param3); await d(param4); From my understanding, this setup works well for a server-based app. Fo ...

Having trouble importing AnimeJS into an Ionic-Angular project

I successfully added AnimeJS to my Ionic 4 project using the commands below: npm i animejs --save npm i @types/animejs --save To reference AnimeJS, I used the following import statement: import * as anime from 'animejs' However, whenever I tr ...

AJV - setting additionalProperties to false with special cases allowed

I have implemented ajv to validate my mongodb schemas. { type: "object", properties: { target: { type: "string" }, budget: { type: "number" } }, required: ["target", "budget"], additionalProperties: ...

What could be causing this conflicting behavior with the logical "and" operator?

const {DEMO, PORT, LOCAL} = process.env; const socketAddress = (DEMO & LOCAL)? `http://${hostname}:${PORT}`: `wss://${hostname}`; When DEMO is false, PORT is undefined, and LOCAL is true The hostname being used is http://9f9cbf19.ngrok.io I verified ...