Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js + require.js + user authentication

Started learning backbone.js and require.js.

Not sure how to structure files for web app with user authentication.

Seems it should flow like this:

  1. On app init, query server to check auth session state;
    • Q#1: where should I be writing this 'after init' session code - in /js/app.js?
    • Q#2: should I be using jQuery ajax for this, or is there better backbone.js methods (I've seen references to get(), fetch(), toJSON() in examples)?
  2. If success, store auth data in a model (user_id, username, auth_token).
    • Q#3: how/where do I init this model so that I can access that data throughout modules? ie. I will have a view to display template for 'isLoggedIn.html' that will read "Hello %username%! Logout". I want to access 'username' field from this model. Currently, I see only how to create a new model by referencing it in the view's define[], so I don't know how to access the model that was created during init.
  3. Will use jQuery $.cookies to save and get this auth data, so if user leaves page and returns, I can query server to check session instead of requiring user to login again.
    • Q#4: how do I include jquery.cookies.js plugin into this requirejs app, so that I can later use $.cookies as usual? Am I supposed to add this plugin to the define[] list? Do I have to add it to the /js/jquery/loader.js file?

Thank you for your assistance.

Edit: I used the files from modular-backbone example to create my web app. So when I am talking about /js/app.js and js/router.js, that's the files I refer to.

like image 578
codemonkey613 Avatar asked May 20 '12 19:05

codemonkey613


1 Answers

I'm in the same situation as well. I found this post and it seems like the best option to do something before every request is to use this solution.

Before accessing and URL except /login, I'm going to authenticate by cookie or run the login view.

About the way to include other folders (jQuery cookie)- just use the require.js mechanism:

  1. In your main file 'require.config' -> 'paths' add the plugin location (jqueryCokkie:)
  2. In your view under 'define' add the path name ('jqueryCookie') and pass it to the finction
  3. The .js file should be in the following structure (I tried to paste the code example here, but got problems...).
like image 70
Roy Tsabari Avatar answered Oct 26 '22 08:10

Roy Tsabari