Re: Re: Session.js

From disqus.com, 2 Months ago, written in JavaScript, viewed 3 times. This paste is a reply to Re: BaseUser.js from disqus.com - view diff
URL https://pastebin.freepbx.org/view/ebcde1e0 Embed
Download Paste or View Raw
  1. define('core/models/Session',[
  2.     'jquery',
  3.     'underscore',
  4.     'backbone',
  5.     'moment',
  6.  
  7.     'core/api',
  8.     'core/bus',
  9.     'core/config',
  10.     'core/time',
  11.     'core/utils',
  12.     'core/utils/cookies',
  13.     'core/utils/guid',
  14.     'core/utils/auth',
  15.  
  16.     'core/models/BaseUser',
  17.     'core/models/User',
  18. ], function (
  19.     $,
  20.     _,
  21.     Backbone,
  22.     moment,
  23.  
  24.     api,
  25.     bus,
  26.     config,
  27.     time,
  28.     utils,
  29.     cookies,
  30.     guid,
  31.     auth,
  32.  
  33.     BaseUser,
  34.     User
  35. ) {
  36.     'use strict';
  37.  
  38.     var fromCookie = function () {
  39.         // Can't move implementation here, as it is imported via auth into React
  40.         // applications. This should be the single access point for this function
  41.         // across embed/home/next-core.
  42.         return auth.getFromCookie();
  43.     };
  44.  
  45.     /**
  46.      * Session is a utility wrapper around a User instance.
  47.      *
  48.      * Usage:
  49.      *
  50.      *   var session = new Session(); // logged out (BaseUser)
  51.      *   var user = new User({ username: 'janedoe' });
  52.      *   session.setUser(user); // logged in
  53.      *
  54.      *
  55.      * You can bind to the session "change" event like so:
  56.      *
  57.      *   session.on('change:id', this.handleSessionChange);
  58.      *
  59.      *
  60.      * Any events fired on the wrapped User model also fire on the Session instance:
  61.      *
  62.      *   session.on('change:display_name', this.handleNameChange);
  63.      *   user.set('display_name', 'Jane Doe'); // => triggers handler
  64.      *
  65.      */
  66.     var Session = Backbone.Model.extend({
  67.  
  68.         initialize: function () {
  69.             // Do the once wrapping upon initialization, not statically, so that
  70.             // fromCookie can be tested. Otherwise it can only be called once per
  71.             // test run.
  72.             this.constructor.fromCookie = _.once(fromCookie);
  73.             this.user = this.getAnonUserInstance();
  74.         },
  75.  
  76.         setUser: function (user) {
  77.             if (this.user)
  78.                 this.stopListening(this.user);
  79.  
  80.             this.user = user;
  81.             this.setIfNewUser();
  82.             this.listenTo(user, 'all', this.trigger);
  83.  
  84.             this.trigger('change:id', user);
  85.         },
  86.  
  87.         isLoggedOut: function () {
  88.             return !this.isLoggedIn();
  89.         },
  90.  
  91.         /**
  92.          * Is the current session authenticated with the server?
  93.          *
  94.          * The current logic just checks if the session user has an ID,
  95.          * but we may change the underlying logic in the future to support
  96.          * situations where we don't yet have the user ID but know that the
  97.          * session is authenticated (of vice versa).
  98.          *
  99.          * @returns {boolean}
  100.          */
  101.         isLoggedIn: function () {
  102.             return Boolean(this.user.get('id'));
  103.         },
  104.  
  105.         fetch: function (options) {
  106.             var opts = options || {};
  107.  
  108.             return api.call('users/details.json', {
  109.                 data: opts.data,
  110.                 success: _.bind(function (response) {
  111.                     response = response.response;
  112.  
  113.                     if (response.id)
  114.                         this.setUser(this.getUserInstance(response));
  115.  
  116.                     if (opts.success) opts.success(response);
  117.                     if (opts.complete) opts.complete(response);
  118.                 }, this),
  119.  
  120.                 error: function (response) {
  121.                     if (opts.error) opts.error(response);
  122.                     if (opts.complete) opts.complete(response);
  123.                 },
  124.             });
  125.         },
  126.  
  127.         getAnonUserInstance: function (attrs) {
  128.             return new BaseUser(attrs);
  129.         },
  130.  
  131.         getUserInstance: function (attrs) {
  132.             return new User(attrs);
  133.         },
  134.  
  135.         getCsrfToken: function () {
  136.             var token = cookies.read('csrftoken');
  137.  
  138.             // We may not always have a token set so if is empty, we set it
  139.             // ourselves. Since Django only compares the token passed in the
  140.             // URL with the value from the cookie, this just works :)
  141.             if (!token) {
  142.                 // Django expects the CSRF token to only contain alphanumeric
  143.                 // characters, and everything else gets replaced.
  144.                 token = guid.generate().replace(/\W/g, '');
  145.                 cookies.create('csrftoken', token, {
  146.                     domain: window.location.hostname,
  147.                     expiresIn: 365 * 24 * 60 * 60 * 1000,  // One year
  148.                 });
  149.             }
  150.  
  151.             return token;
  152.         },
  153.  
  154.         authenticate: function (service) {
  155.             /** @type {Authenticator} */
  156.             var authenticator = this.authServices[service];
  157.             if (!authenticator)
  158.                 return;
  159.  
  160.             if (_.isFunction(authenticator))
  161.                 return authenticator.call(this);
  162.  
  163.             // TODO: move this uiAction event out of Session.
  164.             // It belongs w/ the event handler method that triggers
  165.             // authenticate.
  166.             bus.trigger('uiAction:openLogin', service);
  167.  
  168.             var windowArgs = this.getAuthWindowArgs(authenticator);
  169.             var url = authenticator.url;
  170.             url += (url.indexOf('?') > -1 ? '&' : '?') + $.param(windowArgs);
  171.  
  172.             this.openAuthWindow(
  173.                 url,
  174.                 authenticator.width,
  175.                 authenticator.height
  176.             );
  177.         },
  178.  
  179.         /**
  180.          * An authentication service.
  181.          * @typedef {Object} Authenticator
  182.          * @property {string} url - URL of popup window to initiate authentication.
  183.          * @property {number} width - Width of popup window.
  184.          * @property {number} height - Height of popup window.
  185.          * @property {Object} [params] - Additional parameters to pass to window.
  186.          * @property {boolean} [csrf] - Whether to attach CSRF token as parameter.
  187.          * @property {boolean} [attachExperiment] - Whether to attach experiment
  188.          *     information as a parameter (embed-only).
  189.          */
  190.  
  191.         authServices: {
  192.             /** @type {Authenticator} */
  193.             disqus: {
  194.                 url: config.urls.login,
  195.                 width: 460,
  196.                 height: 355,
  197.                 attachExperiment: true,
  198.             },
  199.  
  200.             /** @type {Authenticator} */
  201.             twitter: {
  202.                 url: config.urls.oauth.twitter,
  203.                 width: 650,
  204.                 height: 680,
  205.                 csrf: true,
  206.                 attachExperiment: true,
  207.             },
  208.  
  209.             /** @type {Authenticator} */
  210.             facebook: {
  211.                 url: config.urls.oauth.facebook,
  212.                 width: 550,
  213.                 height: 300,
  214.                 csrf: true,
  215.                 attachExperiment: true,
  216.             },
  217.  
  218.             /** @type {Authenticator} */
  219.             google: {
  220.                 url: config.urls.oauth.google,
  221.                 width: 445,
  222.                 height: 635,
  223.                 csrf: true,
  224.                 attachExperiment: true,
  225.             },
  226.         },
  227.  
  228.         /**
  229.          * @param {Authenticator} authenticator - Authentication service.
  230.          * @returns {string}
  231.          */
  232.         getAuthWindowArgs: function (authenticator) {
  233.             var windowArgs = {};
  234.  
  235.             if (authenticator.csrf)
  236.                 windowArgs.ctkn = this.getCsrfToken();
  237.  
  238.             _.extend(windowArgs, authenticator.params);
  239.  
  240.             return windowArgs;
  241.         },
  242.  
  243.         openAuthWindow: function (url, width, height) {
  244.             return utils.openWindow(url, '_blank', {
  245.                 width: width,
  246.                 height: height,
  247.             });
  248.         },
  249.  
  250.         /**
  251.          * Tries to determine if session user is a newly registered user and sets a
  252.          * joinedRecently attribute on the user model accordingly.
  253.          *
  254.          * We assume a user is newly registered if account was created in the last 10s.
  255.          */
  256.         setIfNewUser: function () {
  257.             var joinedAt = this.user.get('joinedAt');
  258.  
  259.             // set to false if user is anonymous or doesn't have a joinedAt date set
  260.             if (this.user.get('isAnonymous') || !joinedAt) {
  261.                 this.user.set('joinedRecently', false);
  262.                 return;
  263.             }
  264.  
  265.             var joinedAtUtc = time.assureTzOffset(joinedAt);
  266.  
  267.             // if user joined in the last 10s, set joinedRecently on user model to true
  268.             this.user.set('joinedRecently', moment().subtract(10, 'seconds').isBefore(joinedAtUtc));
  269.         },
  270.  
  271.     });
  272.  
  273.     /**
  274.      * Get session attributes from the `disqusauth` cookie.
  275.      *
  276.      * The `disqusauth` cookie is present on disqus.com whenever
  277.      * a user is logged in with a valid session. It is safe to
  278.      * assume that a user without a disqusauth cookie is not logged
  279.      * in.
  280.      *
  281.      * The `disqusauth` cookie conflates session info with session
  282.      * user info.
  283.      *
  284.      * @returns {Object} Set of session attributes from cookie
  285.      */
  286.     Session.fromCookie = fromCookie;
  287.  
  288.     /**
  289.      * Checks the disqusauth cookie to see if no authenticated session exists.
  290.      *
  291.      * @returns {boolean}
  292.      */
  293.     Session.isKnownToBeLoggedOut = function () {
  294.         return !Session.fromCookie().id;
  295.     };
  296.  
  297.     return Session;
  298. });
  299.  
  300. // https://c.disquscdn.com/next/next-core/core/models/Session.js

Replies to Re: Re: Session.js rss

Title Name Language When
Re: SettingsSocialAccountCollection.js.js disqus.com javascript 2 Months ago.
Re: User.js disqus.com javascript 2 Months ago.

Reply to "Re: Re: Session.js"

Here you can reply to the paste above