Guest User

Untitled

a guest
Oct 13th, 2018
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.91 KB | None | 0 0
  1. var userModel_pd = Backbone.Model.extend({
  2. // Default attributes for the todo item.
  3. defaults: function() {
  4. return {
  5. token: "Token here",
  6. name: "Name here",
  7. householdId: "Household ID here",
  8. householdName: "Household name",
  9. expiration: 0, // need to bind a the log-in event to this object changing to !0
  10. structure: {},
  11. id: 1
  12. };
  13. },
  14.  
  15. //as above, need to bind a the log-in event to this object changing to !0
  16.  
  17. //Set attributes if passed
  18. initialize: function(structure_) {
  19. if (structure_.success == true){
  20. this.setAndSave(structure_);
  21. }
  22. },
  23.  
  24. validCookie: function() { //returns true if cookie hasn't expired and value matches that of userModel, else returns false and reboot() the model
  25. if($.cookie('user')) {return true;} else {this.reboot(); return false;}
  26. },
  27.  
  28. reboot: function() { // Reset.
  29. this.save({token: "Token here", name: "Name here", expiration: 0, householdId: "Household ID here", structure: {}});
  30. console.log('rebooting model');
  31. },
  32.  
  33. setAndSave: function(structure_) {
  34. this.set({name: structure_.currentUser.username, expiration: structure_.expiration, householdId:structure_.currentUser.household.id, householdName: structure_.currentUser.household.name, token: structure_.token, structure: structure_ });
  35. this.save();
  36. }
  37. // **** the change event from reboot should trigger a rerendering in the AppView of sidebar-view and topbar-view
  38. });
  39.  
  40. //COLLECTION: saveduser is used to persist the userModel_pd instance to local storage
  41. var savedUser = Backbone.Collection.extend({
  42. model: userModel_pd,
  43. // Save the user info under the `blue` namespace.
  44. localStorage: new Store("blue-backbone")
  45. });
  46.  
  47. // Create our global User-holder - necessary to store the model to Local Storage
  48. var savedUser_instance = new savedUser;
  49.  
  50. //VIEW: sessionView -- interfaces with DOM inputs, handles the cookie , etc.
  51. var SessionView = Backbone.View.extend({
  52.  
  53. el: $(".login_box"), //Binding to HTML skeleton //(template not needed here), bind to HTML //template: _.template($('#session-template').html());
  54.  
  55. initialize: function() {
  56. // Binding View to DOM Elements // note to self: used to be in initialize function
  57. this.name = this.$('#nameLogin');
  58. this.password = this.$('#passwordLogin');
  59. this.loginButton = this.$('#imgLogin');
  60. this.logoutButton = this.$('#imgLogout');
  61.  
  62. //Look to local storage for an existing user model
  63. savedUser_instance.fetch();
  64.  
  65. // If the userModel's attributes are changed, this (session) View will rerender
  66. //savedUser_instance.bind('add', this.render, this); //this.model.bind('change', this.render(), this);
  67. //savedUser_instance.get(1).bind('change', this.render(), this);
  68. this.model.bind('change', this.render(), this);
  69.  
  70. console.log('before fetch'); console.log('after fetch'); console.log("collection length " + savedUser_instance.length);
  71.  
  72. // If the savedUser collection does not have a userModel, add one
  73. if (savedUser_instance.length == 0){
  74. console.log('instantiate user model');
  75. var userModelglobal = new userModel_pd;
  76. savedUser_instance.add(userModelglobal);
  77. }
  78. //console.log("the sessionView's model token is " + this.model.get('token'));
  79. // If a user model exists, check for a valid cookie
  80. if (savedUser_instance.length){
  81. console.log('checking cookie ' + savedUser_instance.get(1).validCookie());
  82. if (!savedUser_instance.get(1).validCookie()){ // If model does not return valid cookie, reset model
  83. savedUser_instance.get(1).reboot(); // !!!! This triggers a 'change' event, which causes the session View to rerender (see above bound event)
  84. } }
  85. this.render();
  86. },
  87.  
  88. events: // 1.) clicking log in (hitting enter too) calls the ApiCommand to set cookie 2.) Logging out rerenders View
  89. {
  90. "keypress #nameLogin": "pushCredsOnEnter",
  91. "keypress #passwordLogin": "pushCredsOnEnter",
  92. "click #imgLogin": "pushCreds",
  93. "click #imgLogout": "unsetSession"
  94. },
  95.  
  96. render: function() { // 1.) acknowledge a valid cookie by moving the View to the left
  97.  
  98. console.log('rendering session View');
  99.  
  100. if (savedUser_instance.get(1).validCookie()){
  101. //replaceable DOM references
  102. //ACTION SHOULD OCCUR FROM THE CHANGE EVENT, NOT MANUALLY STIPULATED HERE
  103. console.log( savedUser_instance.get(1).get('name') +'has logged-in');
  104. $('#imgLogout').show('slow'); //this.logoutButton.show('slow');
  105. //the below animation is a (non-final) demonstration of state change (having logged in)
  106. //this.$el.hide(); // works
  107. //$('.login_box').hide();
  108. //$('.login_box').css({"position":"relative","right":"100px"}); // animate({"position":"relative","right":"100px"})
  109. //TODO **** stub: render a checkmark image - perhaps in a jquery-esque manner
  110. console.log('again, were here');
  111.  
  112. } else {
  113.  
  114. console.log('original rendering settings');
  115. $('#imgLogout').hide('hide');
  116. this.$el.animate({"position":"relative","right":"0px"});}
  117.  
  118.  
  119. },
  120.  
  121. // If you hit return in either input field, it will attempt to log you in (by pushing credentials)
  122. pushCredsOnEnter: function(e) {
  123. console.log('pushing creds');
  124. if (e.keyCode != 13) return;
  125. if (!this.name.val() && !this.password.val()) return;
  126. this.pushCreds();
  127. this.name.val('');
  128. this.password.val('');
  129.  
  130. },
  131.  
  132. //Take returned JSON, convert it to a Javascript function, set a cookie with those values
  133. pushCreds: function(){
  134. var dataUnique_ = command_center("log_in", {'username_': this.name.val(), 'password_': this.password.val()});
  135. console.log('Callback object from pushCreds ' + dataUnique_);
  136. this.parse_set_cookie(dataUnique_); //SET TWO COOKIES, USER (VALUE = USERNAME), SESSION (VALUE = TOKENID)
  137. savedUser_instance.get(1).setAndSave(dataUnique_); //The set() will trigger a change event, which will call this View's render function
  138. //commented out, because resetting model *should* have been bound to re-rendering view
  139. //this.render();
  140. dataUnique_ = "";
  141. this.render();
  142. },
  143.  
  144. //Take returned JSON, convert it to a Javascript function, set a cookie with those values
  145. unsetSession: function(){
  146. $.cookie('user', null);
  147. $.cookie('session', null);
  148. savedUser_instance.get(1).reboot(); //which, again, should trigger change event which will handle rerendering
  149.  
  150. //commented out, because resetting model should be bound to re-rendering view
  151. //this.render();
  152. },
  153.  
  154. parse_set_cookie: function (jsonFromPHP) {
  155.  
  156. console.log('Json from the Proxy ' + jsonFromPHP);
  157.  
  158. //SETTING TWO COOKIES, MIMICKING THE GREENHOME API PLAYGROUND BEHAVIOR
  159. var thedate=new Date(jsonFromPHP.expiration);
  160.  
  161. myExpiration = thedate.getUTCMilliseconds();
  162. myUsername = jsonFromPHP.currentUser.username;
  163. myToken = jsonFromPHP.token;
  164.  
  165.  
  166. console.log(myUsername);
  167. console.log(myToken);
  168. console.log(myExpiration);
  169.  
  170. $.cookie('user', myUsername, {'expires':myExpiration}); // , {'expires':myExpiration}
  171. $.cookie('session', myToken, {'expires':myExpiration}); // , {'expires':myExpiration}
  172. console.log('Cookie Set ' + $.cookie('user'));
  173. }
  174. });
  175.  
  176. //VIEW ****
  177. // show() or hide() sessionView div. - to be replaced by animation eventually
  178. var appView = Backbone.View.extend({
  179.  
  180. initialize: function() {
  181.  
  182. console.log('instantiating the session View from the App View');
  183.  
  184. //Instantiate the SessionView()
  185. var sessionView_instance = new SessionView({model: userModel_pd});
  186.  
  187. }
  188.  
  189. });
  190.  
  191. var blueApp = new appView;
Add Comment
Please, Sign In to add comment