Philipp Nies
Philipp Nies

Reputation: 969

Node request how to handle sessions

I'm using node.JS with request module.

My problem is, I need to authenticate the user on every request because the session is destroyed outside of the .then((response) => {}) block.

How is it possible to save the created session in a class for later use?

I tried out everything without success.

Here is a not working code snippet

login() {
const getLoginUrl = 'https://www.demourl.com/'
const postLoginUrl = 'https://www.demourl.com/account/login/'

rp({
        url: getLoginUrl,
        jar: this.cookieJar,
        method: 'GET'
    })
    .then((body) => {
        var csrftoken = this.cookieJar.getCookies(getLoginUrl)[1].toString().split('=')[1].split(';')[0];

        var args = {
            url: postLoginUrl,
            json: true,
            method: 'POST',
            data: {
                username: this.username,
                password: this.password
            },
            headers: {
                'method': 'POST',
                'path': '/account/login/',
                'cookie': 'csrftoken=' + csrftoken,
            },
            jar: this.cookieJar,
            resolveWithFullResponse: true
        }

        rp(args)
            .then((response) => {
                //Here is a valid session
                //But how can I use this session in different functions?
                console.log('Post demourl.com/account/login success');
            })
            .catch((error) => {
                console.log('Post demourl.com/account/login error: ', error);
            });
    })
    .catch((error) => {
        console.log('Get demourl.com error: ', error);
        });
}

Upvotes: 1

Views: 180

Answers (2)

Vinno97
Vinno97

Reputation: 524

I never see this.cookieJar being defined. Make sure it's initialized somewhere:

this.cookieJar = request.jar();

If you only use a single cookieJar in your application, you could also use Request's global cookie jar by setting the option jar to true:

// Either by setting it as the default
const request = require('request').defaults({jar: true});

// Or by setting it on each request
request('www.example.com', { jar: true });

Upvotes: 1

Amit Wagner
Amit Wagner

Reputation: 3274

you should use this function as a middleware and then attach what ever you want to attach in to your req

try in you main script do

'use strict'

const express = require('express');
const login = require('./login');
const app = express()


app.use(login);// use this if you want all your routes to check login or put it in a specific route 

app.get('/', (req,res)=>{
//this route is only for loged in users
});

const server = http.createServer(app).listen(process.env.PORT);


module.exports = app;

and in your login script

const login = (req, res, next) => {
    const getLoginUrl = 'https://www.demourl.com/'
    const postLoginUrl = 'https://www.demourl.com/account/login/'

    rp({url: getLoginUrl, jar: this.cookieJar, method: 'GET'})
        .then((body) => {
            var csrftoken = this.cookieJar.getCookies(getLoginUrl)[1].toString().split('=')[1].split(';')[0];

            var args = {
                url: postLoginUrl,
                json: true,
                method: 'POST',
                data: {
                    username: this.username,
                    password: this.password
                },
                headers: {
                    'method': 'POST',
                    'path': '/account/login/',
                    'cookie': 'csrftoken=' + csrftoken,
                },
                jar: this.cookieJar,
                resolveWithFullResponse: true
            }

            rp(args)
                .then((response) => {
                    res.loginResponse = response; // save the response for later use

                    console.log('Post demourl.com/account/login success');
                    next();
                })
                .catch((error) => {
                    console.log('Post demourl.com/account/login error: ', error);
                    return res.send(error) //send the error
                });
        })
        .catch((error) => {
            console.log('Get demourl.com error: ', error);
            return res.send(error)  //send the error
        });
}

module.exports = login

Upvotes: 1

Related Questions