This repository has been archived by the owner on Feb 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
client.js
83 lines (70 loc) · 2.14 KB
/
client.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
/* jshint esnext:true */
/* global LoginToken:true */
/**
* Parse a query string into a key/value object
* @param {String} queryString String to parse
* @return {Object} Key/value object
*/
var parseQueryString = function (queryString) {
return _.object(_.map(queryString
.split('&'),
function (keyval) {
return _.map(keyval.split('='), (val) => decodeURIComponent(val));
}));
};
/**
* Converts an object into a querystring
* @param {Object} obj) Source
* @return {String} Query string
*/
var objectToQueryString = (obj) => _.map(obj, (val, key) => `${key}=${val}`).join('&');
function getParams(str) {
let queryString = str || window.location.search || '';
queryString = queryString.substring(queryString.indexOf('?') + 1);
return parseQueryString(queryString);
}
LoginToken.checkToken = function (token, params, argName = 'authToken') {
if (!token) {
return;
}
const userId = Tracker.nonreactive(Meteor.userId);
let methodArgument = {};
methodArgument[`dispatch_${argName}`] = token;
if (userId) {
LoginToken.emit('loggedInClient');
} else {
Accounts.callLoginMethod({
methodArguments: [methodArgument],
userCallback: function (err) {
if (err) {
LoginToken.emit('errorClient', err);
} else {
LoginToken.emit('loggedInClient');
if (params) {
delete params[argName];
// Make it look clean by removing the authToken from the URL
if (window.history) {
const url =`${window.location.href.split('?')[0]}?${objectToQueryString(params)}`;
window.history.pushState(null, null, url);
}
}
}
},
});
}
};
/**
* Parse querystring for token argument, if found use it to auto-login the
* user
* @param {String} name Name of argument (default "authToken")
*/
LoginToken.autologin = function (name = 'authToken') {
Meteor.startup(function () {
const params = getParams(window.location.search);
if (params[name]) {
LoginToken.checkToken(params[name], params, name);
} else {
LoginToken.emit('noToken');
}
});
};