-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
290 lines (274 loc) · 9.6 KB
/
app.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
//app.js
const ProgramProvider = require('./helpers/programProvider.js');
const AccountInfoProvider = require('./helpers/accountInfoProvider.js');
const Logger = require('./helpers/logger.js');
const ENV = 'dev';
App({
onLaunch: function () {
this.globalData.accessToken = wx.getStorageSync('accessToken');
this.globalData.logger = new Logger(this.globalData.url, ENV);
if (this.globalData.accessToken) {
this.globalData.logger.setAccessToken(this.globalData.accessToken);
}
// Get an instance of AccountInfoProvider
this.globalData.accountInfoProvider = new AccountInfoProvider();
this.globalData.accountInfoProvider.setApiUrl(this.globalData.url);
this.globalData.accountInfoProvider.setLogger(this.globalData.logger);
if (this.globalData.accessToken) {
this.globalData.accountInfoProvider.setAccessToken(this.globalData.accessToken);
}
// Get an instance of ProgramProvider
this.globalData.programProvider = new ProgramProvider();
this.globalData.programProvider.setApiUrl(this.globalData.url);
if (this.globalData.accessToken) {
this.globalData.programProvider.setAccessToken(this.globalData.accessToken);
}
// Start the periodical login status checks.
this.checkLoginStatus();
// Wait 60 seconds and check if the account name is the default.
setTimeout(this.checkDefaultAccountName, 60000);
// Wait 120 seconds to check account validity.
setTimeout(this.checkAccountInfoValidity, 120000);
},
/**
* Solve clients not being logged in properly error by checking periodically
* the login status. Originally the app only checked on startup.
*/
checkLoginStatus: function () {
// Cancel the current timeout if any.
const timeoutId = this.globalData.checkLoginStatusTimeoutId;
if (timeoutId) {
console.debug(`Cancelling current check login status timeout ${timeoutId}`);
clearTimeout(timeoutId);
}
// Check if the user session is still valid
console.debug('Checking login status');
wx.checkSession({
success: res => {
// Check if the accountInfoProvider needs to fetch an auth_token
if (!this.globalData.accountInfoProvider.ready()) {
const message = 'User session is valid but account info provider not ready, requesting wx.login()';
console.warn(message);
this.globalData.logger.log({
message,
res,
req: 'wx.checkSession()',
extra: {'accountInfo' : this.globalData.accountInfoProvider.toString()},
level: 1,
page: 'app.js',
method: 'checkLoginStatus',
line: '60'
});
this.requestLogin();
} else {
// Current session is active and we have an access token.
// Add slow periodic checks.
this.globalData.checkLoginStatusTimeoutId = setTimeout(this.checkLoginStatus, 30000);
}
},
fail: res => {
// WX user session has expired, we need to renew the session_key
console.debug('User session has expired, calling wx.login()');
this.requestLogin();
}
});
},
/**
* Request user login against the wx backend. We will obtain a
* temporary JS code that can be sent to the minihiker.com backend
* to obtain permanent user openid and temporary session_key.
*/
requestLogin: function () {
console.debug('Requesting wx.login()');
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
// Authenticate the user on the backend
this.loginUser(res.code);
},
fail: err => {
const message = 'wx.login() failed';
this.globalData.logger.log({
message,
res: err,
req: 'wx.login()',
extra: { 'accountInfo': this.globalData.accountInfoProvider.toString() },
level: 1,
page: 'app.js',
method: 'requestLogin',
line: '100'
});
console.error(message, err);
},
complete: res => {
// Set periodic login status checks.
clearTimeout(this.globalData.checkLoginStatusTimeoutId);
this.globalData.checkLoginStatusTimeoutId = setTimeout(this.checkLoginStatus, 30000);
}
});
},
/** Send login information to the backend to authenticate user. */
loginUser: function (code) {
const url = this.globalData.url + 'wx-auth';
const method = 'POST';
const data = { jsCode: code };
const header = { 'Content-Type': 'application/json' };
wx.request({
url,
method,
data,
header,
success: res => {
const accessToken = res.data.access_token;
if (accessToken) {
console.debug(`Obtained access token ${accessToken} from backend.`);
this.setAccessToken(accessToken);
} else {
const message = `Unexpected backend login response. Access token '${accessToken}'`;
this.globalData.logger.log({
message,
res,
req: { url, method, data, header },
extra: { 'accountInfo': this.globalData.accountInfoProvider.toString() },
level: 1,
page: 'app.js',
method: 'loginUser',
line: '140'
});
console.error(msg, res);
}
// YHT
wx.setStorageSync('userId', res.data.user_id);
},
fail: err => {
const message = 'Error loggin user in against MH backend.';
this.globalData.logger.log({
message,
res: err,
req: { url, method, data, header },
extra: { 'accountInfo': this.globalData.accountInfoProvider.toString() },
level: 1,
page: 'app.js',
method: 'loginUser',
line: '155'
});
console.error(message, err);
}
});
},
/** Set globally the access token */
setAccessToken: function (accessToken) {
wx.setStorage({
key: 'accessToken',
data: accessToken,
success: () => { console.debug('Saved user access token to storage.') },
fail: () => {
const message = 'Error saving user access token to storage.';
this.globalData.logger.log({
message,
res: 'fail',
req: 'wx.setStorage',
extra: {
'accountInfo': this.globalData.accountInfoProvider.toString(),
key, data
},
level: 1,
page: 'app.js',
method: 'setAccessToken',
line: '160'
});
console.error(message);
}
});
this.globalData.accessToken = accessToken;
this.globalData.programProvider.setAccessToken(accessToken);
this.globalData.accountInfoProvider.setAccessToken(accessToken);
this.globalData.logger.setAccessToken(accessToken);
},
/**
* Check wether the currently stored account info is considered still valid.
*/
checkAccountInfoValidity: function () {
console.debug('Checking Account information validity');
this.globalData.accountInfoProvider.checkAccountInfoValidity().then(res => {
if (res.error) {
const message = 'Invalid account info detected';
this.globalData.logger.log({
message,
res,
req: 'accountInfoProvider.checkAccountInfoValidity()',
extra: { 'accountInfo': this.globalData.accountInfoProvider.toString() },
level: 1,
page: 'app.js',
method: 'checkAccountInfoValidity',
line: '215'
});
console.error(message);
this.requestLogin();
} else {
console.debug('Account information is still valid.');
}
}).catch(err => {
const message = 'Invalid account info error.';
this.globalData.logger.log({
message,
res: err,
req: 'accountInfoProvider.checkAccountInfoValidity()',
extra: { 'accountInfo': this.globalData.accountInfoProvider.toString() },
level: 1,
page: 'app.js',
method: 'checkAccountInfoValidity',
line: '230'
});
console.error(message);
this.requestLogin();
});
setTimeout(this.checkAccountInfoValidity, 120000);
},
/**
* Check if the clients have updated the default user name.
*/
checkDefaultAccountName: function () {
if (this.globalData.accountInfoProvider.name === '未注册') {
wx.showModal({
title: '请更新信息',
content: '请点击确定按钮,修改您的昵称和微信号,方便报名活动后,我们邀请您进入活动群',
success: res => {
if (res.confirm) {
// The user agrees to go update their details now.
wx.navigateTo({
url: '/pages/edit-account-details/edit-account-details',
});
}
}
});
}
},
/**
* @deprecated, clients should switch to calling log directly on the
* logger instance.
*/
log: function (data) {
console.warn('Calling deprecated method app.log(), please update your code to use logger.log()');
this.globalData.logger.log(data);
},
globalData: {
accessToken: null,
logger: null,
programProvider: null,
accountInfoProvider: null,
payments: null,
url: 'https://wxapiv1.minihiker.com/',
resUrl: 'https://static.minihiker.com/',
staticUrl: 'https://static.minihiker.com/',
webviewUrl: 'https://backend.minihiker.com/',
// url: 'http://wxapi.mh/',
// resUrl: 'http://static.mh/',
// staticUrl: 'http://static.mh/'
/**
* Store the ID of the current timeout for the checkLoginStatus to avoid
* having more than one timeout running at the same time.
*/
checkLoginStatusTimeoutId: null,
}
})