57a60d41d7
Return sessionToken from login endpoints and store it client-side because wx.request cannot rely on Set-Cookie. Also fix multi-cookie parsing, start on login page, and guard chat rendering fields. Co-authored-by: Cursor <cursoragent@cursor.com>
99 lines
2.6 KiB
JavaScript
99 lines
2.6 KiB
JavaScript
const {
|
|
checkAuth,
|
|
loginWithPassword,
|
|
loginWithWechatCode,
|
|
isTouristMode,
|
|
getApiBaseUrl
|
|
} = require('../../utils/api');
|
|
const { MINIAPP_LOGIN_PATH } = require('../../utils/config');
|
|
|
|
Page({
|
|
data: {
|
|
username: '',
|
|
password: '',
|
|
error: '',
|
|
wechatLoading: false,
|
|
passwordLoading: false,
|
|
touristWarning: '',
|
|
envHint: ''
|
|
},
|
|
|
|
onLoad() {
|
|
this.refreshEnvHints();
|
|
this.tryAutoLogin();
|
|
},
|
|
|
|
refreshEnvHints() {
|
|
const apiBaseUrl = getApiBaseUrl();
|
|
let touristWarning = '';
|
|
let envHint = '';
|
|
|
|
if (isTouristMode()) {
|
|
touristWarning =
|
|
'游客模式:微信一键登录不可用。请用 AppID wx3e79ecd530c88da4 重新导入项目,并确认 DevTools 登录微信号已是小程序管理员。';
|
|
}
|
|
if (/127\.0\.0\.1|localhost/i.test(apiBaseUrl)) {
|
|
envHint = '当前连本地 Portal;请确保已运行 pnpm dev 并已重启。';
|
|
}
|
|
|
|
this.setData({ touristWarning, envHint });
|
|
},
|
|
|
|
async tryAutoLogin() {
|
|
try {
|
|
const status = await checkAuth();
|
|
if (status?.authenticated) {
|
|
const app = getApp();
|
|
if (status.user) {
|
|
app.globalData.user = status.user;
|
|
}
|
|
wx.switchTab({ url: '/pages/chat/index' });
|
|
}
|
|
} catch {
|
|
// Stay on the login page when the existing session cannot be verified.
|
|
}
|
|
},
|
|
|
|
handleUsername(event) {
|
|
this.setData({ username: event.detail.value, error: '' });
|
|
},
|
|
|
|
handlePassword(event) {
|
|
this.setData({ password: event.detail.value, error: '' });
|
|
},
|
|
|
|
async handleWechatLogin() {
|
|
this.setData({ wechatLoading: true, error: '' });
|
|
try {
|
|
await loginWithWechatCode(MINIAPP_LOGIN_PATH);
|
|
wx.switchTab({ url: '/pages/chat/index' });
|
|
} catch (error) {
|
|
this.setData({
|
|
error:
|
|
error?.message ||
|
|
'微信登录暂不可用。若后端尚未开放小程序登录接口,请先使用 H5 账号登录。'
|
|
});
|
|
} finally {
|
|
this.setData({ wechatLoading: false });
|
|
}
|
|
},
|
|
|
|
async handlePasswordLogin() {
|
|
const username = this.data.username.trim();
|
|
const password = this.data.password;
|
|
if (!username || !password) {
|
|
this.setData({ error: '请输入用户名和密码' });
|
|
return;
|
|
}
|
|
this.setData({ passwordLoading: true, error: '' });
|
|
try {
|
|
await loginWithPassword(username, password);
|
|
wx.switchTab({ url: '/pages/chat/index' });
|
|
} catch (error) {
|
|
this.setData({ error: error?.message || '登录失败,请重试' });
|
|
} finally {
|
|
this.setData({ passwordLoading: false });
|
|
}
|
|
}
|
|
});
|