-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
104 lines (96 loc) · 3.29 KB
/
index.html
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
97
98
99
100
101
102
103
104
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tweeter</title>
</head>
<body>
<div>
<p id="message">Loading...</p>
<button id="reload" onclick="reloadTweet();">Reload</button>
<div id="tweets"></div>
</div>
<script>
var authorizaionUrl = 'http://localhost:9999/uaa';
var tweeterApiUrl = 'http://localhost:8082/v1';
var clientId = 'demo';
var TweeterApp = function (location) {
this.params = this.paramsFromHash(location.hash);
};
TweeterApp.prototype.checkToken = function (location) {
if (!(this.params && this.params.access_token)) {
// redirect
var redirectUri = location.href;
location.href = authorizaionUrl + '/oauth/authorize?client_id=' + clientId + '&response_type=token&redirect_uri=' + redirectUri;
return false;
} else {
// Remove hash
location.hash = '';
return true;
}
};
TweeterApp.prototype.accessToken = function () {
return this.params.access_token;
};
TweeterApp.prototype.userinfo = function () {
return this.httpGet(authorizaionUrl + '/userinfo');
};
TweeterApp.prototype.tweets = function () {
return this.httpGet(tweeterApiUrl + '/tweets');
};
TweeterApp.prototype.httpGet = function (url) {
return new Promise(function (resolve, reject) {
var r = new XMLHttpRequest();
r.open('GET', url, true);
r.setRequestHeader('Authorization', 'Bearer ' + this.accessToken());
r.onreadystatechange = function () {
if (r.readyState === 4) {
if (r.status !== 200) {
console.error(r);
reject(r);
} else {
resolve(JSON.parse(r.responseText));
}
}
};
r.send();
}.bind(this));
};
TweeterApp.prototype.paramsFromHash = function (hash) {
hash = hash.charAt(0) === '#' ? hash.substring(1) : hash;
var params = {},
regex = /([^&=]+)=([^&]*)/g,
m;
while ((m = regex.exec(hash)) !== null) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
if (params.access_token || params.error) {
return params;
}
};
document.addEventListener('DOMContentLoaded', function () {
window.app = new TweeterApp(location);
if (!window.app.checkToken(location)) {
return;
}
// Load
window.app.userinfo()
.then(function (user) {
console.log(user);
document.getElementById('message').innerText = 'Hello ' + user.firstName + ' ' + user.lastName + '!';
});
var loadTweets = function () {
window.app.tweets()
.then(function (tweets) {
var list = tweets.map(function (t) {
return '<li>' + t.text + '</li>';
}).join('');
document.getElementById('tweets').innerHTML = '<ul>' + list + '</ul>';
})
};
loadTweets();
document.getElementById('reload').onclick = loadTweets;
});
</script>
</body>
</html>