source: OKFNAnnotator (for Zope)/annotator_files/lib/plugin/auth.js @ 3:6356e78ccf5c

Last change on this file since 3:6356e78ccf5c was 3:6356e78ccf5c, checked in by casties, 12 years ago

new version contains Annotator JS files to be used with FilesystemSite?.

File size: 5.7 KB
Line 
1var base64Decode, base64UrlDecode, createDateFromISO8601, parseToken,
2  __hasProp = Object.prototype.hasOwnProperty,
3  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
4
5createDateFromISO8601 = function(string) {
6  var d, date, offset, regexp, time, _ref;
7  regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" + "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" + "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
8  d = string.match(new RegExp(regexp));
9  offset = 0;
10  date = new Date(d[1], 0, 1);
11  if (d[3]) date.setMonth(d[3] - 1);
12  if (d[5]) date.setDate(d[5]);
13  if (d[7]) date.setHours(d[7]);
14  if (d[8]) date.setMinutes(d[8]);
15  if (d[10]) date.setSeconds(d[10]);
16  if (d[12]) date.setMilliseconds(Number("0." + d[12]) * 1000);
17  if (d[14]) {
18    offset = (Number(d[16]) * 60) + Number(d[17]);
19    offset *= (_ref = d[15] === '-') != null ? _ref : {
20      1: -1
21    };
22  }
23  offset -= date.getTimezoneOffset();
24  time = Number(date) + (offset * 60 * 1000);
25  date.setTime(Number(time));
26  return date;
27};
28
29base64Decode = function(data) {
30  var ac, b64, bits, dec, h1, h2, h3, h4, i, o1, o2, o3, tmp_arr;
31  if (typeof atob !== "undefined" && atob !== null) {
32    return atob(data);
33  } else {
34    b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
35    i = 0;
36    ac = 0;
37    dec = "";
38    tmp_arr = [];
39    if (!data) return data;
40    data += '';
41    while (i < data.length) {
42      h1 = b64.indexOf(data.charAt(i++));
43      h2 = b64.indexOf(data.charAt(i++));
44      h3 = b64.indexOf(data.charAt(i++));
45      h4 = b64.indexOf(data.charAt(i++));
46      bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
47      o1 = bits >> 16 & 0xff;
48      o2 = bits >> 8 & 0xff;
49      o3 = bits & 0xff;
50      if (h3 === 64) {
51        tmp_arr[ac++] = String.fromCharCode(o1);
52      } else if (h4 === 64) {
53        tmp_arr[ac++] = String.fromCharCode(o1, o2);
54      } else {
55        tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
56      }
57    }
58    return tmp_arr.join('');
59  }
60};
61
62base64UrlDecode = function(data) {
63  var i, m, _ref;
64  m = data.length % 4;
65  if (m !== 0) {
66    for (i = 0, _ref = 4 - m; 0 <= _ref ? i < _ref : i > _ref; 0 <= _ref ? i++ : i--) {
67      data += '=';
68    }
69  }
70  data = data.replace(/-/g, '+');
71  data = data.replace(/_/g, '/');
72  return base64Decode(data);
73};
74
75parseToken = function(token) {
76  var head, payload, sig, _ref;
77  _ref = token.split('.'), head = _ref[0], payload = _ref[1], sig = _ref[2];
78  return JSON.parse(base64UrlDecode(payload));
79};
80
81Annotator.Plugin.Auth = (function(_super) {
82
83  __extends(Auth, _super);
84
85  Auth.prototype.options = {
86    token: null,
87    tokenUrl: '/auth/token',
88    autoFetch: true
89  };
90
91  function Auth(element, options) {
92    Auth.__super__.constructor.apply(this, arguments);
93    this.waitingForToken = [];
94    if (this.options.token) {
95      this.setToken(this.options.token);
96    } else {
97      this.requestToken();
98    }
99  }
100
101  Auth.prototype.requestToken = function() {
102    var _this = this;
103    this.requestInProgress = true;
104    return $.ajax({
105      url: this.options.tokenUrl,
106      dataType: 'text',
107      xhrFields: {
108        withCredentials: true
109      }
110    }).done(function(data, status, xhr) {
111      return _this.setToken(data);
112    }).fail(function(xhr, status, err) {
113      var msg;
114      msg = Annotator._t("Couldn't get auth token:");
115      console.error("" + msg + " " + err, xhr);
116      return Annotator.showNotification("" + msg + " " + xhr.responseText, Annotator.Notification.ERROR);
117    }).always(function() {
118      return _this.requestInProgress = false;
119    });
120  };
121
122  Auth.prototype.setToken = function(token) {
123    var _results,
124      _this = this;
125    this.token = token;
126    this._unsafeToken = parseToken(token);
127    if (this.haveValidToken()) {
128      if (this.options.autoFetch) {
129        this.refreshTimeout = setTimeout((function() {
130          return _this.requestToken();
131        }), (this.timeToExpiry() - 2) * 1000);
132      }
133      this.updateHeaders();
134      _results = [];
135      while (this.waitingForToken.length > 0) {
136        _results.push(this.waitingForToken.pop()(this._unsafeToken));
137      }
138      return _results;
139    } else {
140      console.warn(Annotator._t("Didn't get a valid token."));
141      if (this.options.autoFetch) {
142        console.warn(Annotator._t("Getting a new token in 10s."));
143        return setTimeout((function() {
144          return _this.requestToken();
145        }), 10 * 1000);
146      }
147    }
148  };
149
150  Auth.prototype.haveValidToken = function() {
151    var allFields;
152    allFields = this._unsafeToken && this._unsafeToken.issuedAt && this._unsafeToken.ttl && this._unsafeToken.consumerKey;
153    return allFields && this.timeToExpiry() > 0;
154  };
155
156  Auth.prototype.timeToExpiry = function() {
157    var expiry, issue, now, timeToExpiry;
158    now = new Date().getTime() / 1000;
159    issue = createDateFromISO8601(this._unsafeToken.issuedAt).getTime() / 1000;
160    expiry = issue + this._unsafeToken.ttl;
161    timeToExpiry = expiry - now;
162    if (timeToExpiry > 0) {
163      return timeToExpiry;
164    } else {
165      return 0;
166    }
167  };
168
169  Auth.prototype.updateHeaders = function() {
170    var current;
171    current = this.element.data('annotator:headers');
172    return this.element.data('annotator:headers', $.extend(current, {
173      'x-annotator-auth-token': this.token
174    }));
175  };
176
177  Auth.prototype.withToken = function(callback) {
178    if (!(callback != null)) return;
179    if (this.haveValidToken()) {
180      return callback(this._unsafeToken);
181    } else {
182      this.waitingForToken.push(callback);
183      if (!this.requestInProgress) return this.requestToken();
184    }
185  };
186
187  return Auth;
188
189})(Annotator.Plugin);
Note: See TracBrowser for help on using the repository browser.