-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (55 loc) · 1.66 KB
/
index.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
'use strict';
(function() {
var AUTH_TOKEN = 'authToken';
var AUTH_FIELDS = ['access-token', 'client', 'expiry', 'uid'];
var STORAGE_ERR = 'Storage must implement `getItem`, `setItem`, and `removeItem`';
var storage = window.localStorage;
function isFunction(maybeFunc) {
return typeof maybeFunc === 'function';
}
function isValidStorage(customStorage) {
customStorage = customStorage || {};
return (
isFunction(customStorage.getItem) &&
isFunction(customStorage.setItem) &&
isFunction(customStorage.removeItem)
);
}
function getAuth() {
var auth = storage.getItem(AUTH_TOKEN);
if (auth) return JSON.parse(auth);
return {};
}
function parseHeaders(headers) {
return AUTH_FIELDS.reduce(function(memo, field) {
memo[field] = headers.get(field);
return memo;
}, { 'token-type': 'Bearer' });
}
function isSignedIn() {
var auth = getAuth();
var token = auth['access-token'];
var expiryInMs = parseInt(auth.expiry, 10) * 1000;
return !!(token && expiryInMs && Date.now() < expiryInMs);
}
function persistToken(headers) {
storage.setItem(AUTH_TOKEN, JSON.stringify(parseHeaders(headers)));
}
function removeToken() {
storage.removeItem(AUTH_TOKEN);
}
function requestHeaders() {
return getAuth();
}
function setStorage(customStorage) {
if (!isValidStorage(customStorage)) {
throw new Error(STORAGE_ERR)
}
storage = customStorage;
}
exports.isSignedIn = isSignedIn;
exports.persistToken = persistToken;
exports.removeToken = removeToken;
exports.requestHeaders = requestHeaders;
exports.setStorage = setStorage;
}).call(this);