Secure User Validation Using ExpressJS and CouchDB

I am currently working on implementing a CouchDB User login into my express app using a frontend form and storing the login information in the session. Here is what I have done so far:

In my app.js file:

var express = require('express');
var couchUser = require('express-user-couchdb');
var session = require('express-session');

var login = require('./routes/login');

var app = express();

app.use(couchUser({
    users: 'http://localhost:5984/_users',
    request_defaults: {
        auth: {
            user: 'admin',
            pass: 'adminpw'
        }
    }
}));

app.use(session({ secret: 'secretstring'}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', login);

And in my login.js file:

var express = require('express');
var router = express.Router();
var couchUser = require('express-user-couchdb');

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.render('login', {title: 'Login'});
});

router.post('/login', function(req, res) {
    // This section needs to be filled based on requirements
    //res.send(req.body.username)
});

module.exports = router;

I am seeking guidance on how to proceed with the route in my login.js file. Any assistance would be greatly appreciated.

An update - I encountered issues with the previous code due to lack of clarity, after further research I found a solution that worked for me:

router.post('/', function(req, res) {

    var options = {
        url: 'http://localhost:5984/_session',
        method: 'POST',
        json: {
            "name": "admin",
            "password": "password"
        }
    };


    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log('authenticated');
        }else{
            console.log('not authenticated');
            res.redirect('/')
        }
    });
});

When testing the same request using HttpRequester, I received a Statuscode 200 along with {"ok":true,"name":null,"roles":["_admin"]}. However, when attempting it through Node.js, it did not work as expected even though the requests were similar. Any insights on this discrepancy?

Answer №1

If you need to verify user credentials against CouchDB, refer to the guidance provided in the CouchDB documentation.

curl -X POST http://localhost:5984/_session -d 'name=jan&password=apple'

Once authentication is successful, store the CouchDB credentials in the session storage.

I have drafted a "proof of concept" script that may not be flawless as I am not an expert in Node.js. With some adjustments and fine-tuning, it should function correctly.

var http = require('http');

router.post('/login', function(req, res) {
    var session = req.session;
    request.post('http://localhost:5984/_session')
        .auth(req.data.username, req.data.password, true)
        .on('response', function(response) {
            if(response.statusCode == 200) {
                session.couchSession = req.data.username + ':' + req.data.password;
                res.status(200);
                res.send();
            } else {
                res.status(400);
                res.send('Wrong credentials');
            }
        });
});

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

Cookie Cutter Chrome Extensions

Is there a way to create a cookie that can be shared between my plugin and contentPage? I've tried creating one but it doesn't seem to appear on the cookie list of the tab page. Any suggestions or ideas on how to achieve this? ...

how to transfer data from backend servlet to frontend javascript

Hey, I'm still learning about servlets so please excuse any confusion in my message! So basically, I'm trying to figure out how to pass a value from a servlet to JavaScript or even retrieve values from a servlet method within JavaScript. But I&ap ...

Tips for properly aligning an image within an owl carousel

Currently, I am attempting to center a small image within the owl carousel. While I have managed to center it when it's active and in the center, I'm encountering issues when the item no longer carries the "center" class. You can access Owlcarou ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

Arranging a string array in JavaScript according to an integer array

Looking at the provided javascript arrays: letterArray ['a', 'e', 'i', 'o', 'u'] We also have another array that corresponds to it: valueArray [12, 22, 7, 7, 3] The goal is to sort the valueArray into: ...

What is the best approach for querying an entry by a specific attribute, such as name, in a MongoDB database using Express?

In this setup, an express server is communicating with a mongoDb server through mongoose. The goal here is to locate and retrieve a specific entry by name in the /getCollege/:name route without resorting to the findbyid function. const express = require( ...

Error: The Tabs component is expecting a different `value`. The Tab with the current `value` ("0") is not present in the document structure

I am encountering an issue while using MUI tabs. The error message I receive is as follows: MUI: The value assigned to the Tabs component is not valid. The Tab with this value ("0") does not exist in the document layout. Please ensure that the tab item is ...

Update the span's content according to the user's input

Is it possible to update the value of a span to match that of an input field in HTML? HTML: <p style='font-size:150%'> Hey friend, I am <span id='name_display'>Anonymous</span>, I'd like to invite you to..... &l ...

Retrieve an item from the Ionic Firebase database

My current challenge is retrieving data from the Firebase database. user-service.ts getProfile(){ try {; return this.afDatabse.object(`profile/${this.afAuth.auth.currentUser.uid}`); } catch (e) { console.log(e); } } c ...

Transmitting JSON AJAX response to populate location markers on Google Maps

When a button is clicked, an AJAX response is triggered to display JSON data based on a search query. My goal is to take the all_locations variable from the AJAX response and use it to show markers on a Google map. I'm uncertain about how to achieve t ...

Assigning a value to a variable can prevent the occurrence of an

My recursive code consists of two pieces aiming to print out half of the array recursively until we reach arrays of length 1. Surprisingly, the code without variable assignment runs infinitely, while the code with variable assignment behaves as expected. ...

Modify the properties of an element based on another

Situation : I am facing a challenge where I need to adjust two components based on a click event. The function linked to the onclick event handleChange includes a prop 'text'. Each time the onclick event is triggered, I must modify the value of t ...

Content within a Row of a Data Table

Hello! I am just starting to learn JavaScript and jQuery. Can you help me with an issue I am experiencing? Basically, I have a table and I need to identify which tr contains a td with the text "Weekly", "Daily", or "Monthly". Once I locate that specific t ...

Interactive YouTube Video Player that keeps video playing in original spot upon clicking the button

Currently, I'm working on a project that involves combining navigation and a video player within the same div container. Here is an image link And another image link The concept is that when you click on one of the four boxes, a new video will appe ...

Create a new CSS rule within a class, and remember to save the changes to

Upon opening page 1.html, I utilize JavaScript to dynamically add a background image to the body of the page. To achieve this, I use the following code: document.body.style.backgroundImage = "url(http://www.example.com/image.jpg)"; This code effectively ...

Tips for integrating Laravel's blade syntax with Vuejs

Can you guide me on integrating the following Laravel syntax into a Vue.js component? @if(!Auth::guest()) @if(Auth::user()->id === $post->user->id) <a href=#>edit</a> @endif @endif ...

Lost Connection with nodejs, express, cors, and the express-session package

Currently developing a backend system using nodejs, express, express-session, cors, and cookie-parser to interact with a react application that utilizes axios for sending http requests. The database being used is mariadb. Everything functions perfectly wh ...

What is the process for adjusting the input value dynamically in reactjs?

I am working on a dynamic time input row and I need to ensure that the values are updated correctly. This is the code snippet I am using: https://codesandbox.io/s/624vq8y7y3 When I run the code, the values in the TimeInput field do not change as expected ...

Ways to check if a user is logged in on a mobile application

As I embark on creating my very first mobile app with user login functionality, I find myself at a crossroads when it comes to determining the best way to store the logged-in status. The app will interact with backend webservices on my website, allowing u ...

Error: JSON parsing error encountered due to an unexpected token 'U' while trying to read a file with

Currently, I am utilizing Node.js version 12.14.1 and encountering a problem while attempting to parse a JSON file that includes the \U0001f970 character. The file's content that needs to be read and parsed is as follows: {"randomKey": ...