Skip to content

Instantly share code, notes, and snippets.

@anextro
Created September 18, 2015 19:27
Show Gist options
  • Save anextro/f749afba4f5dc617338d to your computer and use it in GitHub Desktop.
Save anextro/f749afba4f5dc617338d to your computer and use it in GitHub Desktop.
Backbone Authentication Model and its usage by a subsystem to resolve a route
//actual auth.js
/**
* module name: auth
* role: It answers the query; Is the User Logged In
* @param url: Endpoint to make request
* @param state: The predicate
*/
module.exports = Backbone.Model.extend({
url: "/api/admin/checkAuthentication",
defaults: function(){
return {
state: false
};
}
});
//a file showing its usage
home: function(){
/**
* Delegates to authenticator to load login page or default page
*/
this.auth.fetch({
success: function(mod, res, opt){
opt.self.rootview.showViews({header: HeadView, content: {view: ContentView, path: null}, footer: null});
},
error: function(mod, res, opt){
opt.self.rootview.showViews({header: HeadView, content: {view: LoginView, path: null}, footer: null});
},
self: this
});
},
@ianmstew
Copy link

Instead of showing your views imperatively based on success/error callbacks, try switching it so that which view you show is dependent on your auth model. This is closer to the Backbone pattern that all view changes are rooted in a model change.

this.auth.fetch().then(function () {
  if (this.auth.get('state')) {
    // show content view
  } else {
    // show login view
  }
});

This implies that you have re-written /api/admin/checkAuthentication on the back end to return status 200 every time, except { state: true } if authenticated and { state: false } if not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment