-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtokenauth.js
97 lines (80 loc) · 2.61 KB
/
tokenauth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"use strict";
var jwt = require('jwt-simple');
var annotator = require('annotator');
var _t = annotator.util.gettext;
function TokenIdentityPolicy (token) {
this.token = token;
}
TokenIdentityPolicy.prototype.who = function () {
return this.token;
};
TokenIdentityPolicy.prototype.setToken = function (token) {
this.token = token;
this.payload = jwt.decode(token, null, false);
}
function TokenAuthzPolicy () {
annotator.authz.AclAuthzPolicy.call(this);
}
TokenAuthzPolicy.prototype = Object.create(annotator.authz.AclAuthzPolicy.prototype);
TokenAuthzPolicy.prototype.constructor = annotator.authz.AclAuthzPolicy;
TokenAuthzPolicy.prototype.authorizedUserId = function (identity) {
var payload = jwt.decode(identity, null, false);
return payload.userId;
};
var tokenauth = function (options) {
options = options || {
token: null,
tokenUrl: '/auth/token',
autoFetch: true
};
var identityPolicy = new TokenIdentityPolicy(options.token);
var authorizationPolicy = new TokenAuthzPolicy();
var notify = console.log;
var fetchToken = function() {
return $.ajax({
url: options.tokenUrl,
dataType: 'text',
xhrFields: {
withCredentials: true
}
}).fail(function(xhr, status, err) {
var msg;
msg = _t("Couldn't get auth token:");
console.error("" + msg + " " + err, xhr);
return notify("" + msg + " " + xhr.responseText, annotator.notification.ERROR);
});
};
var haveValidToken = function() {
var payload = identityPolicy.payload;
var allFields = payload && payload.issuedAt && payload.ttl && payload.consumerKey;
if (allFields) {
return true;
} else {
return false;
}
};
return {
configure: function (registry) {
registry.registerUtility(identityPolicy, 'identityPolicy');
registry.registerUtility(authorizationPolicy, 'authorizationPolicy');
},
start: function (app) {
notify = app.registry.queryUtility('notifier') || notify;
if (!options.token) {
return fetchToken(options.tokenUrl).then(function (tok) {
identityPolicy.setToken(tok);
});
}
}
};
};
// app.include(...tokenauth, {token: 'ABCDE'})
//
// OR
//
// app.include(...tokenauth, {tokenUrl: '/auth/token'})
// app
// .start()
// .then(function () {
// app.annotations.store.setHeader('X-Annotator-Auth-Token', app.ident.token);
// })