feat: login rest

This commit is contained in:
Blizzard
2026-02-12 09:26:39 +08:00
parent e97fd30fa3
commit 5553e2711a
115 changed files with 4090 additions and 3499 deletions
+49 -16
View File
@@ -2,39 +2,72 @@ import request from './utils/request';
App({
onLaunch() {
// Login
// Initialize login process immediately
this.loginPromise = new Promise((resolve, reject) => {
this._resolveLogin = resolve;
this._rejectLogin = reject;
});
this.doLogin();
},
// Perform actual login
doLogin() {
wx.login({
success: res => {
// Send res.code to backend to swap for openId, sessionKey, unionId
if (res.code) {
request.get('/auth/miniLogin', { code: res.code }).then(data => {
// Response structure based on user input: { user: {...}, token: "...", expiresAt: ... }
// Note: request.js might return data.user directly if it unwraps 'data'
// But looking at previous request.js usage, it seems to return the 'data' field of the response.
// Let's handle both cases safely.
request.get('/auth/miniLogin', { code: res.code }).then(async (data) => {
const token = data.token;
const user = data.user;
if (token && typeof token === 'string') {
wx.setStorageSync('token', token);
if (user) {
wx.setStorageSync('userInfo', user);
this.globalData.userInfo = user;
}
console.log('Login successful, user info stored');
console.log('Login successful');
if (this._resolveLogin) this._resolveLogin(token);
// Background Profile Update
request.get('/profile/detail').then(userDetail => {
if (userDetail) {
wx.setStorageSync('userInfo', userDetail);
this.globalData.userInfo = userDetail;
}
}).catch(e => {
console.error('Fetch profile detail failed on launch', e);
// Fallback
if (data.user) {
wx.setStorageSync('userInfo', data.user);
this.globalData.userInfo = data.user;
}
});
} else {
console.warn('Login response did not contain a valid token', data);
console.warn('Login response invalid', data);
if (this._rejectLogin) this._rejectLogin('No token');
}
}).catch(err => {
console.error('Login failed', err);
console.error('Login API failed', err);
if (this._rejectLogin) this._rejectLogin(err);
});
} else {
console.error('wx.login failed: ' + res.errMsg);
if (this._rejectLogin) this._rejectLogin(res.errMsg);
}
},
fail: err => {
if (this._rejectLogin) this._rejectLogin(err);
}
});
},
// Method for other pages/utils to wait for login
ensureLogin() {
// If token exists, resolve immediately
const token = wx.getStorageSync('token');
if (token) return Promise.resolve(token);
// Return existing promise or create new if failed previously?
// For simplicity, return the launch promise.
// In robust apps, handle token expiration and re-login here.
return this.loginPromise;
},
globalData: {
userInfo: null
}