Session.js

From disqus.com, 7 Months ago, written in Plain Text, viewed 3 times.
URL https://pastebin.freepbx.org/view/af37a6ac Embed
Download Paste or View Raw
  1. define('home/models/Session',[
  2.     'jquery',
  3.     'underscore',
  4.     'backbone',
  5.  
  6.     'core/api',
  7.     'core/models/Session',
  8.     'core/UniqueModel',
  9.  
  10.     'home/models/User',
  11.     'home/models/UserProfile',
  12.     'home/models/AnonUser',
  13.     'home/models/Notifications',
  14.     'home/utils/backboneUtils',
  15.     'home/utils/sidebarUtils',
  16. ], function (
  17.     $,
  18.     _,
  19.     Backbone,
  20.  
  21.     api,
  22.     SharedSession,
  23.     UniqueModel,
  24.  
  25.     User,
  26.     UserProfile,
  27.     AnonUser,
  28.     Notifications,
  29.     BackboneUtils,
  30.     SidebarUtils
  31. ) {
  32.     'use strict';
  33.  
  34.     var Session = SharedSession.extend({
  35.         initialize: function () {
  36.             SharedSession.prototype.initialize.apply(this, arguments);
  37.             this.moderatedForums = []; // array of forum ids that this user moderates
  38.             this._load = $.Deferred();
  39.             this._loadPromise = this._load.promise();
  40.  
  41.             // Load may not be called more than once per Session instance.
  42.             this.load = _.once(this.load, this);
  43.             this.loadModeratedForums = _.once(this.loadModeratedForums, this);
  44.         },
  45.  
  46.         // Overridden from parent. This returns the usr instance to use
  47.         // when no user is logged in.
  48.         getAnonUserInstance: function (attrs) {
  49.             return new AnonUser(attrs);
  50.         },
  51.  
  52.         isAnonymous: function () {
  53.             return this.user.get('isAnonymous');
  54.         },
  55.  
  56.         setUser: function (user) {
  57.             if (this.user)
  58.                 this.stopListening(this.user);
  59.  
  60.             this.listenTo(user, 'all', this.trigger);
  61.  
  62.             return SharedSession.prototype.setUser.apply(this, arguments);
  63.         },
  64.  
  65.         /**
  66.          * Load session user's moderated forums.
  67.          *
  68.          * Returns immediately if disqusauth cookie indicates user
  69.          * is not a moderator. Otherwise makes a network request.
  70.          *
  71.          * This method is memoized with `_.once`.
  72.          * @returns {Promise}
  73.          */
  74.         loadModeratedForums: function () {
  75.             var user = this.user;
  76.             var self = this;
  77.  
  78.             if (Session.fromCookie().isModerator) {
  79.                 // When the session logs in, we look to see what forums the
  80.                 // session user moderates
  81.                 return Backbone.ajax({
  82.                     url: api.getURL('internal/users/details'),
  83.                     success: function (data) {
  84.                         var moderatedForums = data.response.moderated_forums;
  85.                         self.moderatedForums = moderatedForums;
  86.                         self.trigger('setModeratedForums', moderatedForums);
  87.                         user.set({
  88.                             isModerator: Boolean(moderatedForums.length),
  89.                             moderatedForums: moderatedForums,
  90.                         });
  91.                     },
  92.                     context: user,
  93.                 });
  94.             }
  95.  
  96.             return $.Deferred().resolve().promise();
  97.         },
  98.  
  99.         /**
  100.          * Who is providing user authentication and details for this session?
  101.          *
  102.          * @returns {string} account type or '' if there is no session information
  103.          */
  104.         provider: function () {
  105.             var username = Session.fromCookie().username;
  106.             if (!username)
  107.                 return '';
  108.  
  109.             return username.indexOf('-') === -1 ? 'disqus' : username.split('-')[0];
  110.         },
  111.  
  112.         fromSessionStorage: function () {
  113.             var attrs;
  114.             try {
  115.                 attrs = JSON.parse(window.sessionStorage[Session.STORAGE_KEY]);
  116.                 delete window.sessionStorage[Session.STORAGE_KEY];
  117.             } catch (err) {
  118.                 // Pass
  119.             }
  120.             return _.isObject(attrs) ? attrs : undefined;
  121.         },
  122.  
  123.         /**
  124.          * Load the session.
  125.          *
  126.          * First looks at session storage. If not there, determines if user is logged
  127.          * out based on the disqusauth cookie. If user is logged in, kicks off a network
  128.          * fetch call.
  129.          * Resolves or rejects the promise returned by `this.session.loadPromise()`.
  130.          *
  131.          * This method is memoized with `_.once`.
  132.          */
  133.         load: function () {
  134.             var load = this._load;
  135.  
  136.             // First we check if we can load a valid user from
  137.             // session storage. We assume the user is valid if the
  138.             // attributes have a username and an ID.
  139.             //
  140.             // Only do this in the sidebar, because home uses User attrs
  141.             // that are not set in sessionstorage
  142.             var userAttrs = this.fromSessionStorage();
  143.             if (SidebarUtils.isSidebar() && userAttrs && userAttrs.username && userAttrs.id) {
  144.                 this.setUser(this.getUserInstance(userAttrs));
  145.                 this.fetched = true;
  146.                 load.resolve(this);
  147.             }
  148.  
  149.             // If we didn't load from sesssion storage, we should
  150.             // check if we think the user is even logged in.
  151.             else if (!SharedSession.isKnownToBeLoggedOut()) {  // eslint-disable-line no-negated-condition
  152.  
  153.                 var self = this;
  154.                 self.fetch()
  155.                     .done(function () { load.resolve(self); })
  156.                     .fail(function () { load.reject(self); });
  157.             }
  158.  
  159.             else {
  160.                 load.reject(this);
  161.             }
  162.         },
  163.  
  164.         loadPromise: function () {
  165.             return this._loadPromise;
  166.         },
  167.  
  168.         fetch: function () {
  169.             if (this.fetchPromise)
  170.                 // Return early if we're already fetching so we don't
  171.                 // bind handlers multiple times
  172.                 return this.fetchPromise;
  173.  
  174.             var self = this;
  175.             var fetchPromise = BackboneUtils.memoizedFetch.apply(this, arguments);
  176.  
  177.             // The base/shared session does not go through Backbone,
  178.             // so sync/error events are not properly fired. Thus, we
  179.             // are left with creating our own
  180.             fetchPromise.then(function () {
  181.                 self.trigger('fetch:success');
  182.             }, function () {
  183.                 self.trigger('fetch:error');
  184.             });
  185.  
  186.             return fetchPromise;
  187.         },
  188.  
  189.         getUserInstance: function (attrs) {
  190.             return new UniqueModel(
  191.                 User,
  192.                 attrs
  193.             );
  194.         },
  195.  
  196.         getUserProfile: function () {
  197.             if (this.isAnonymous())
  198.                 return;
  199.  
  200.             return this.userProfile;
  201.         },
  202.  
  203.         getOrCreateNotifications: function () {
  204.             if (!this.notifications) {
  205.                 this.notifications = new Notifications({ session: this });
  206.                 this.notifications.ensureFetched();
  207.             }
  208.  
  209.             return this.notifications;
  210.         },
  211.  
  212.         toJSON: function () {
  213.             return this.user.toJSON.apply(this.user, arguments);
  214.         },
  215.  
  216.         /**
  217.          * Creates the userProfile model for the session user.
  218.          * @param  {string} username - The username of the session user.
  219.          */
  220.         initUserProfile: function (username) {
  221.             if (!username)
  222.                 return;
  223.  
  224.             // Unbind listeners on previous user profile
  225.             if (this.userProfile)
  226.                 this.userProfile.stopListening(this);
  227.  
  228.             this.userProfile = new UniqueModel(UserProfile, {
  229.                 username: username,
  230.             });
  231.  
  232.             var markChannelsOrForums = function (forums) {
  233.                 // Check if given a single forum because items:sync may be a propagated
  234.                 // event from a single item in the collection.
  235.                 // Wrap forum as an underscore collection, as function expects.
  236.                 if (forums instanceof Backbone.Model)
  237.                     forums = _([forums]);
  238.  
  239.                 forums.each(function (forum) {
  240.                     // If this is a channel, make sure we're marking its primary forum
  241.                     if (forum.primaryForum)
  242.                         forum = forum.primaryForum;
  243.  
  244.                     forum.set('isFollowing', true);
  245.                 });
  246.             };
  247.             // Listen for when following forums are loaded so that they can be
  248.             // properly marked as followed by the session user
  249.             this.userProfile.forumsFollowing.on('items:sync', markChannelsOrForums);
  250.             this.userProfile.channelsFollowing.on('items:sync', markChannelsOrForums);
  251.  
  252.             // Listen for when the session user (un)follows a forum/user, so the user profile's
  253.             // following collections can be properly updated
  254.             var followingUsers = this.userProfile.following.get('items');
  255.             var followingForums = this.userProfile.forumsFollowing.get('items');
  256.             var followingChannels = this.userProfile.channelsFollowing.get('items');
  257.             this.userProfile.listenTo(this, 'followed:user', _.bind(followingUsers.add, followingUsers));
  258.             this.userProfile.listenTo(this, 'unfollowed:user', _.bind(followingUsers.remove, followingUsers));
  259.             this.userProfile.listenTo(this, 'followed:forum', _.bind(followingForums.add, followingForums));
  260.             this.userProfile.listenTo(this, 'unfollowed:forum', _.bind(followingForums.remove, followingForums));
  261.             this.userProfile.listenTo(this, 'followed:channel', _.bind(followingChannels.add, followingChannels));
  262.             this.userProfile.listenTo(this, 'unfollowed:channel', _.bind(followingChannels.remove, followingChannels));
  263.  
  264.             this.fetchFollowedForums();
  265.             this.fetchFollowedChannels();
  266.         },
  267.  
  268.         /**
  269.          * Fetches the list of forums the session user is following (up to 100) so that they can
  270.          * be marked as followed. This is so that we can indicate to the user correctly when they
  271.          * see a forum whether or not they are following it, as that information is not returned
  272.          * in forum details from the api.
  273.          *
  274.          * Written as a separate function so that the asEmbedApp can overwrite with a no-op, as
  275.          * the sidebar does not need it for all routes. Will be manually called by each view
  276.          * if necessary. Currently needed for forum profile and user profile following forums tab.
  277.          */
  278.         fetchFollowedForums: function () {
  279.             this.userProfile.fetchForumsFollowing();
  280.         },
  281.  
  282.         fetchFollowedChannels: function () {
  283.             this.userProfile.fetchChannelsFollowing();
  284.         },
  285.  
  286.         logout: function () {
  287.             this.setUser(this.getAnonUserInstance());
  288.             window.top.location = '//disqus.com/logout/?redirect=http%3A%2F%2Fdisqus.com';
  289.         },
  290.     }, {
  291.         STORAGE_KEY: 'home.session',
  292.     });
  293.  
  294.  
  295.     // Linter wants the definition moved to the top of the file, defining it here close
  296.     // to use is more readable.
  297.     var _session;  // eslint-disable-line one-var
  298.  
  299.     Session.get = function () {
  300.         _session = _session || new Session();
  301.         return _session;
  302.     };
  303.  
  304.     // Normally this method should only be used by tests
  305.     Session.forget = function () {
  306.         if (_session) {
  307.             _session.stopListening();
  308.             _session.off();
  309.             _session = null;
  310.         }
  311.     };
  312.  
  313.     return Session;
  314. });
  315.  
  316. //https://c.disquscdn.com/next/82c6de3/home/js/models/Session.js

Replies to Session.js rss

Title Name Language When
Re: Session.js disqus.com javascript 7 Months ago.

Reply to "Session.js"

Here you can reply to the paste above