Adrian
Adrian

Reputation: 631

App-wide authentication handler for Javascript functions?

What is the best approach to handle authentication on a bunch of Javascript actions on a page without littering the code base with "if authenticated()" checks?

For example: we have 10 like buttons, some comment buttons and a few other actions that require authentication. When a user is not authenticated, we want to redirect them to a login/signup page. However, we want to avoid littering the code with if (user.isAuthenticated()) { xxx } calls. In our particular case we want to use these mostly for events in backbone, although I don't think that matters for the general question.

Upvotes: 1

Views: 196

Answers (2)

KooiInc
KooiInc

Reputation: 123026

How about creating a method that does the checking, using a callback for the method that should be called if authentication is ok? Something like:

function checkNdRun(cb,params){
  params = [].slice.call(params);
  if (/*[authenticationCheckingLogic here]*/){
    cb.apply(null,params);
  } else {
    alert('please login first');
  }
}
//usage example
somebutton.onclick = 
     function(e){checkNdRun(functionToRun,e,/*[other parameters]*/);};

Upvotes: 0

qianfg
qianfg

Reputation: 898

With the help of underscorejs. You can write something like this:

function authWrapper(func){
    if (user.isAuthenticated()) {
     func.apply(this, _.rest(arguments));
    }else{
       ...
    }
}

Suppose you're using jQuery, when binding the events, write this:

$(...).bind('event', _.wrap(function(...){...}, authWrapper));

or

$(...).bind('event', _.wrap(thehandler, authWrapper));

Upvotes: 1

Related Questions