Janis F
Janis F

Reputation: 2630

Understanding how to use NodeJS to create a simple backend

I have been trying to develop a rather simple server in nodejs. Basically, what I am going for is a simple API that requires authentication (simple username/password style). What I do not need is any kind of frontend functionality (templating etc.). My problem is, I can't seem to get my head around the approach of express/node.

Specifically, my questions are:

As I mentioned earlier, I believe my problem is ultimately a difficulty with the function-oriented approach in node (also, I have rather limited experience in webservice programming). If you know a resource where I could read up on how to approach architecting a nodejs app, please don't hesitate to point me to it.

Upvotes: 6

Views: 20891

Answers (4)

deitch
deitch

Reputation: 14581

If you are looking for REST, I recommend using either Restify or booster

For authentication (distinct from authorization), use standard Basic, which can be handled by express.basicAuth() just to parse it and place it on the req object. Personally, I don't like basicAuth because it returns a 401 if there is no login, whereas the process of authenticating is different than determining if authentication is necessary.

For more advanced authentication, as well as session management, use cansecurity or passport. For authorization, you either can put individual middleware in each route, use cansecurity's middlewares, or use its declarative authorization.

Disclosure: I am the author of both booster and cansecurity.

Upvotes: 1

Jazor
Jazor

Reputation: 282

A simple way to implement authentication (if you don't want to use additional modules):

var checkAuth = function(req, res, next) {
  if(!req.session.user)
  {
    // Redirect to login form
    res.redirect("/login");
  }
  else
  {
    // Proceed to member's area
    next();
  }
};

app.get("/member/page", checkAuth, function(req, res) {
  // render view, etc
});

bodyParser parses / converts the body of a POST request into an object, which helps with getting form submission values.

The route that handles your login form submission can access username / password like this:

var username = req.body.username;
var password = req.body.password;

At this point you'd query your database to select from users where the username and password matches (you'd want to use password encryption in a production environment).

If you get a record back in the query result, set it in the session. A simple way to do this is:

req.session.user = userRecord

(Adjust for your session middleware)

Upvotes: 1

Krasimir
Krasimir

Reputation: 13529

How do I wire in the authentication? Do I pass several handlers into every route that requires authentication, or is there a more elegant way to do this?

You should use the session middleware. Here is some pseudo code:

var http = require('http');
var app = express();

var authorize = function(req, res, next) {
    if(req.session && req.session.appname && req.session.appname === true) {
        // redirect to login page
        return;
    }
    next();
}

app.use(express.session());
app.all('/admin*', authorize, function(req, res, next) {

});

How does the Express middleware (like app.use(express.bodyParser())) work? Do they alter contents of the request or response object? Specifically, if I use the body parser (internally formidable?), where do I access the request data this is supposed to parse?

Every middleware have an access to the request and response object. So, yes, it modifies it. Normally attach properties to it. This means that inside your handler (which is also a middleware) you may write:

if(req.body && req.body.formsubmitted && req.body.formsubmitted === 'yes') {
    var data = {
        title: req.body.title,
        text: req.body.text,
        type: req.body.type
    }
    // store the data
}

When using authentication and I have, say, credentials stored in a database with more information about the individual client associated, at what point do I extract that information? I.e., when a user logs in, do I fetch the user record on login and pass it on, or do I fetch it in every handler that requires the information?

I think that you should do the things the same way as in any other server side language. Keep the state of the user (logged/not-logged) inside a session. You may also keep the user's id and fetch the data for him whatever you need. It depends of your case, but you have the ability to cache information. Because node is not like PHP for example, I mean it's not dieing.

Ultimately, do you know of an open source application that I could take a look at? I'd like to see something that has simple authentication and maybe even utilizes formidable, since uploading a file is one of my requirements.

Yep. I wrote an article about really simple MVC web site with admin panel. It is available here. And the code of it is here.

Upvotes: 4

Leprosy
Leprosy

Reputation: 1135

If your goal is to build a RESTful API in Node.js, my best bet would be Restify, which uses a similar aproach of routes like Express, but eliminates all the high level stuff(templating, etc.) and ads backend functionalities(ie: body parser, ip blacklist, requests per hour).

For the authentication part, I would use another library perhaps, and wire it to a particular route. There are ORM's too that can solve your database needs(mongo and mysql are well supported, both for the "noSQL" fans and the classic db aproach ones).

Upvotes: 0

Related Questions