source: OKFNAnnotator (for Zope)/annotator_files/lib/plugin/auth.js @ 4:6979313586cf

Last change on this file since 4:6979313586cf was 4:6979313586cf, checked in by casties, 12 years ago

new version of annotator.

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