auth.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. (function (Misago) {
  2. 'use strict';
  3. var Auth = function(_) {
  4. var self = this;
  5. _.user = _.models.deserialize('user', _.context.user);
  6. // Auth state synchronization across tabs
  7. this.isDesynced = false; // becomes true if auth state between tabs differs
  8. this.newUser = null; // becomes user obj to which we want to sync
  9. var handleAuthChange = function(isAuthenticated) {
  10. if (!self.isDesynced) {
  11. m.startComputation();
  12. // display annoying "you were desynced" message
  13. self.isDesynced = true;
  14. if (isAuthenticated) {
  15. self.newUser = _.localstore.get('auth-user');
  16. }
  17. m.endComputation();
  18. }
  19. };
  20. var handleUserChange = function(newUser) {
  21. if (!self.isDesynced) {
  22. m.startComputation();
  23. if (_.user.id !== newUser.id) {
  24. self.isDesynced = true;
  25. self.newUser = newUser;
  26. } else if (newUser) {
  27. _.user = $.extend(_.user, newUser);
  28. }
  29. m.endComputation();
  30. }
  31. };
  32. var syncSession = function() {
  33. _.localstore.set('auth-user', _.user);
  34. _.localstore.set('auth-is-authenticated', _.user.isAuthenticated);
  35. _.localstore.watch('auth-is-authenticated', handleAuthChange);
  36. _.localstore.watch('auth-user', handleUserChange);
  37. };
  38. syncSession();
  39. // Shorthand for signing user components out
  40. var switchMount = function(mountId) {
  41. var mount = document.getElementById(mountId);
  42. var component = null;
  43. if (mount) {
  44. component = mount.dataset.componentName;
  45. m.mount(
  46. mount, _.component(component.replace('user-nav', 'guest-nav')));
  47. }
  48. };
  49. this.signOut = function() {
  50. _.user.isAuthenticated = false;
  51. _.user.isAnonymous = true;
  52. syncSession();
  53. switchMount('user-menu-mount');
  54. switchMount('user-menu-compact-mount');
  55. };
  56. };
  57. Misago.addService('auth',
  58. function(_) {
  59. return new Auth(_);
  60. },
  61. {
  62. after: 'model:user'
  63. });
  64. }(Misago.prototype));