Megidd
Megidd

Reputation: 7952

NPM resourceful package connection to couchdb gives error, while using passport for user-authentication

I have the following JavaScript code which tries to connect to CouchDB with resourceful in order to make a user database model for passport user-authentication. An error occurs at the line this.use('couchdb'); as follows:

Error

at Request._onResponse [as _callback] (/home/ict/Documents/hookahDB/serverjs/node_modules/cradle/lib/cradle.js:232:29)

at Request.self.callback (/home/ict/Documents/hookahDB/serverjs/node_modules/request/request.js:186:22)

at emitTwo (events.js:106:13)

at Request.emit (events.js:191:7)

at Request. (/home/ict/Documents/hookahDB/serverjs/node_modules/request/request.js:1081:10)

at emitOne (events.js:96:13)

at Request.emit (events.js:188:7)

at IncomingMessage. (/home/ict/Documents/hookahDB/serverjs/node_modules/request/request.js:1001:12)

at IncomingMessage.g (events.js:292:16)

at emitNone (events.js:91:20)

//NPM express package is employed
//express package looks like an express lane which takes you to your destination very fast
//it is a high-level layer on top of low-level HTTP calls
var express = require('express')
var app = express()

//the port at which node.js loop is running and listening:
//on our host machine to access the node.js we need to go to the following address with a web browser:
//http://127.0.0.1:10002/
const port = process.env.PORT || 10002

//to retrieve HTML5 form input texts from body of POST request, we need NPM `body-parser` package
//later on, we need to retrieve username & password from HTML5 form
//here is the difference between `json` and `urlencoded`:
// assuming POST: name=foo&color=red            <-- URL encoding
// or       POST: {"name":"foo","color":"red"}  <-- JSON encoding
var bodyParser = require('body-parser');
app.use(bodyParser.json()); //to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
    extended: true
}));

//public directory from which we are serving the static files
//CSS3 stylesheets are located in `public` directory
//files which are absolutely static without any dynamic content would be in `public`
app.use(express.static(__dirname + '/public'))

//template engine: EJS
//EJS is a template engine which preserves HTML5 syntax and is very popular
//I like to work with HTML5 syntax which is familiar, therefore I choose EJS
app.set('view engine', 'ejs');

//homepage url at '/'
//this is the url of our homepage at which username and password is asked
app.get('/', function(req, res) {
    res.render('index.ejs');
})

//NPM package passport is used as the user-authentication method
//passport is very popular now
var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy;

var flash = require('connect-flash');
var session = require('express-session');

//middleware: some middleware is required to initialize passport:
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(session({
    secret: 'secret',
    name: 'session id',
    saveUninitialized: true,
    resave: true
}));

//The user id (we provide as the second argument of the done function) is saved in the session and is later used to retrieve the whole object via the deserializeUser function.
//serializeUser determines, which data of the user object should be stored in the session
//The result of the serializeUser method is attached to the session as req.session.passport.user = {}
//Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id:'xyz'}
passport.serializeUser(function(user, done) {
    //done(null, user.id);
    done(null, user._id);
});
//
passport.deserializeUser(function(id, done) {
    /*User.findById(id, function(err, user) {
        done(err, user);
    });*/
    User.find({ _id: id }, function(err, user) {
        if (err || user.length == 0)
            done(err, null);
        else
            done(err, user[0]);
    });
});

//a user data model is needed
//we are going to use CouchDB based on our preliminary studies on tech-selection
//NPM resourceful package has a simplified data-model-management which supports CouchDB
//We are going to use resourceful package
var resourceful = require('resourceful');
resourceful.use('couchdb', { database: 'passport-test' });
var User = resourceful.define('user', function() {
    //specify a storage engine
    //error happens at this line:
    //When uncommenting this line, the above-mentioned error won't happen:
    this.use('couchdb');
    //specify some properties with validation
    this.string('username');
    this.string('password');
    //we don't need `id` since CouchDB assigns an `_id` to every document
    //this.number('id');
    // Specify timestamp properties
    //I'm not sure how timestamp works, but API documentations are using it
    this.timestamps();
})

//we need to define a local Strategy to authenticate with username and password
passport.use(new LocalStrategy(

    function(username, password, done) {
        process.nextTick(function() {
            User.find({
                username: username
            }, function(err, user) {
                if (err) {
                    return done(err);
                }
                if (!user || user.length == 0) {
                    return done(null, false, {
                        message: 'Incorrect username: ' + username
                    });
                }
                user = user[0];
                if (user.password != password) {
                    return done(null, false, {
                        message: 'Incorrect password.'
                    });
                }
                return done(null, user);
            });
        })
    }
));

//login page url at '/login'
//after asking username & password by HTML5 form, user is redirected to `/login` url
app.post('/login',
    passport.authenticate('local', {
        successRedirect: '/profile',
        failureRedirect: '/',
        failureFlash: true
    })
);

//When user can log in, he/she will be going to `/profile` url
app.get('/profile', function(req, res) {
    res.render('profile.ejs')
})

//run nodejs loop to be listening at port number specifiled at the top of the code
app.listen(port, function(err) {
    if (err) {
        throw err
    }
    console.log('server is listening on ' + port + ' ...')
})

On CouchDB we have a passport-test database as follows:

Screenshot of passport-test database on CouchDB

I wonder if anybody knows how I can resolve this error. I have searched and tried some solutions, but I couldn't make it work.

Upvotes: 0

Views: 143

Answers (1)

Megidd
Megidd

Reputation: 7952

I ended up using cradle rather than resourceful to use couchdb

Upvotes: 0

Related Questions