-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
142 lines (119 loc) · 2.9 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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import { define } from '@xinix/xin';
import { Middleware } from '@xinix/xin/components';
import qs from 'qs';
import jwt from 'jsonwebtoken';
const { btoa, atob, location, localStorage } = window;
class XinAccountMiddleware extends Middleware {
get props () {
return Object.assign({}, super.props, {
location: {
type: Object,
value: () => location,
},
storage: {
type: Object,
value: () => localStorage,
},
baseUrl: {
type: String,
},
clientId: {
type: String,
},
});
}
callback () {
return async (ctx, next) => {
let hash = this.location.hash;
if (hash.startsWith('#access_token=')) {
try {
let authData = qs.parse(hash.substr(1));
this.save(authData.access_token);
try {
let state = JSON.parse(atob(authData.state));
this.location.replace(`#!${state.uri}`);
} catch (err) {
this.location.replace(`#!/`);
}
await sleep(300);
return;
} catch (err) {
throw err;
}
}
this.init();
await this.refresh();
if (!this.token) {
this.signin();
await sleep(300);
return;
}
await next();
};
}
init () {
if (this.token) {
return;
}
let token = this.storage.APP_TOKEN;
if (token && !this.decode(token)) {
this.invalidate();
token = undefined;
}
this.save(token);
}
signin () {
let state = btoa(JSON.stringify({
uri: this.location.hash.split('#!').pop(),
}));
this.location.href = `${this.baseUrl}/oauth/auth?client_id=${this.clientId}&response_type=token&response_mode=fragment&state=${state}`;
}
signout () {
this.invalidate();
this.location.href = `${this.baseUrl}/oauth/signout?client_id=${this.clientId}`;
}
async refresh () {
try {
let resp = await window.fetch(`${this.baseUrl}/oauth/refresh`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
access_token: this.token,
}),
});
if (resp.status === 401) {
return this.invalidate();
}
if (resp.status === 200) {
let body = await resp.json();
if (!body.access_token) {
return this.invalidate();
}
this.save(body.access_token);
}
} catch (err) {
// noop
}
}
save (token = '') {
if (token) {
this.storage.APP_TOKEN = token;
} else {
delete this.storage.APP_TOKEN;
}
this.token = token;
this.fire('token-change', token);
}
invalidate () {
this.save();
}
decode (token) {
return jwt.decode(token);
}
}
define('xin-account-middleware', XinAccountMiddleware);
function sleep (t = 0) {
return new Promise(resolve => setTimeout(resolve, t));
}