node-auth-rest-server

0.1.7 • Public • Published

AuthRestServer

Provides a basic token authentication, and auto generation of authentication token

Based on express.

How to use

npm install node-auth-rest-server

and then in your application

// use express
var app = express();

// inject authRest middleware
var authRest = require('node-auth-rest-server');
app.use(authRest(app, authRestMethods, '/api/secret/'));

Here authRestMethods is a javascript object that implements the following method:

authRestMethods = {
    userByEmail: function(email, callback) {
      // your code here
      // e.g. SELECT * FROM auth_users WHERE email = ?
      callback(err, user);
    },
    newAuthToken: function(key, userId, expiresAt, callback){
      // your code here
      // e.g. INSERT INTO auth_tokens SET ?
      // SELECT * FROM auth_tokens where id = insertId
      callback(err, authToken);
    },
    getValidTokenByUser: function(user, callback){
      // your code here
      // e.g. SELECT * FROM auth_tokens where user_id = ? and expires_at > ?
      callback(err, authToken);
    },
    getValidTokenByKey: function(authTokenKey, callback){
      // your code here
      // e.g. SELECT * FROM auth_tokens where `key` = ? and expires_at > ?
      callback(err, authToken);
    },
    isAuthorizedUrl: function(url){
      // e.g.
      // return url.indexOf('/api/secret/') == 0;
    }
};

The flow

  • the server recieves a request to a url
  • authRest middleware checks if the url starts with the prefix that is passed to it, e.g. /api/secret/ as in the example:
// inject authRest middleware
var authRest = require('node-auth-rest-server');
app.use(authRest(app, authRestMethods));
  • if the authRestMethods.isAuthorizedUrl(url) returns false, then the middleware doesn't perform the following steps and just calls next
  • if the header doeasn't contain any token then the request ends with respond 401
  • calls authRestMethods.getValidTokenByKey with the token from the header and in it's callback checks the value
  • if there is such a token, then the middleware doesn't do anything elseand just calls next, otherwise the request ends with respond 401

If the client gets 401 response it should perform POST to /api/sessions/get_auth_token

The middleware actually adds POST /api/sessions/get_auth_token to the router. When such a request is received by the the server, the middleware performs the authToken generation by calling getAuthToken (check the implementation for more details).

Package Sidebar

Install

npm i node-auth-rest-server

Weekly Downloads

0

Version

0.1.7

License

none

Last publish

Collaborators

  • alexlibs