124 lines
2.5 KiB
JavaScript
124 lines
2.5 KiB
JavaScript
const { API } = require('./constants');
|
|
const { request } = require('./http');
|
|
|
|
function wechatLoginCode() {
|
|
return new Promise((resolve, reject) => {
|
|
wx.login({
|
|
success(res) {
|
|
if (res && res.code) resolve(res.code);
|
|
else reject(new Error('wx.login: missing code'));
|
|
},
|
|
fail(err) {
|
|
reject(err);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
async function loginWithEncryptedData({ encryptedData, iv, rawData, signature }) {
|
|
const code = await wechatLoginCode();
|
|
|
|
// POST /api/oauth/login
|
|
const loginData = await request({
|
|
path: API.wechatLogin,
|
|
method: 'POST',
|
|
needAuth: false,
|
|
data: {
|
|
code,
|
|
encryptedData,
|
|
iv,
|
|
rawData,
|
|
signature
|
|
},
|
|
contentType: 'application/json'
|
|
});
|
|
|
|
const app = getApp();
|
|
const accessToken = loginData && typeof loginData.accessToken === 'string' ? loginData.accessToken : '';
|
|
const openid = loginData && typeof loginData.openid === 'string' ? loginData.openid : '';
|
|
|
|
app.setAuth({
|
|
accessToken,
|
|
openid
|
|
});
|
|
|
|
// Try fetch profile; if token is invalid backend should return error.
|
|
let myProfile = null;
|
|
try {
|
|
myProfile = await request({
|
|
path: API.myProfile,
|
|
method: 'GET',
|
|
needAuth: true
|
|
});
|
|
} catch (e) {
|
|
// Keep login usable even if profile fetch fails
|
|
myProfile = null;
|
|
}
|
|
|
|
if (myProfile && typeof myProfile === 'object') {
|
|
app.setAuth({
|
|
userProfile: myProfile
|
|
});
|
|
}
|
|
|
|
return {
|
|
loginData,
|
|
myProfile
|
|
};
|
|
}
|
|
|
|
async function fetchMyProfile() {
|
|
return request({
|
|
path: API.myProfile,
|
|
method: 'GET',
|
|
needAuth: true
|
|
});
|
|
}
|
|
|
|
async function fetchMyAuth() {
|
|
return request({
|
|
path: API.myAuth,
|
|
method: 'GET',
|
|
needAuth: true
|
|
});
|
|
}
|
|
|
|
async function submitMyAuth({ name, mobile, idCardNumber, idCardImageUrl, idCardBackImageUrl }) {
|
|
const payload = {
|
|
name,
|
|
mobile,
|
|
idCardNumber
|
|
};
|
|
if (idCardImageUrl) payload.idCardImageUrl = idCardImageUrl;
|
|
if (idCardBackImageUrl) payload.idCardBackImageUrl = idCardBackImageUrl;
|
|
|
|
return request({
|
|
path: API.myAuth,
|
|
method: 'POST',
|
|
needAuth: true,
|
|
data: payload,
|
|
contentType: 'application/json'
|
|
});
|
|
}
|
|
|
|
async function fetchMyRegistrations({ pageNo = 1, pageSize = 10 } = {}) {
|
|
return request({
|
|
path: API.myRegistrations,
|
|
method: 'GET',
|
|
needAuth: true,
|
|
data: {
|
|
PageNo: pageNo,
|
|
PageSize: pageSize
|
|
}
|
|
});
|
|
}
|
|
|
|
module.exports = {
|
|
loginWithEncryptedData,
|
|
fetchMyProfile,
|
|
fetchMyAuth,
|
|
submitMyAuth,
|
|
fetchMyRegistrations
|
|
};
|
|
|