Browse Source

登陆验证

pull/106/head
pengda 3 weeks ago
parent
commit
79ad0e5fe0
  1. 6
      src/main.js
  2. 61
      src/utils/login.js

6
src/main.js

@ -66,10 +66,12 @@ Vue.use(clipboard);
Vue.directive('clickaway', clickaway);
Vue.mixin(HeaderIcon)
// ✅ 自动登录后再启动应用
autoLoginByToken().finally(() => {
autoLoginByToken().then(() => {
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
})
}).catch(() => {
window.location.href = process.env.VUE_APP_HOST;
});

61
src/utils/login.js

@ -2,24 +2,57 @@
import axios from 'axios'
export async function autoLoginByToken() {
// axios 带超时机制
function axiosWithTimeout(promise, ms) {
return Promise.race([
promise,
new Promise((_, reject) => setTimeout(() => reject(new Error('请求超时')), ms))
]);
}
export async function autoLoginByToken(timeout = 10000) {
const urlParams = new URLSearchParams(window.location.search)
const token = urlParams.get('token')
if (token) {
try {
const res = await axios.post(process.env.VUE_APP_BASE_API+'/agentnew/token_login', { token: token },{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
})
if (res.data.status) {
const res = await axiosWithTimeout(
axios.post(
process.env.VUE_APP_BASE_API+'/agentnew/token_login',
new URLSearchParams({ token })
),
timeout
);
if(!res.data.status){
throw new Error('登陆失败');
}
// 可选:将 token 存入 localStorage
localStorage.setItem('token', res.data.data.access_token)
localStorage.setItem('nick', res.data.data.nick)
}
const res = await axiosWithTimeout(
axios.post(
process.env.VUE_APP_BASE_API+'/agentnew/check_login',{}, // 保证和 x-www-form-urlencoded 匹配
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
),
timeout
);
if(!res.data.status){
throw new Error('您还未登陆');
}
const access_token = localStorage.get('token')
if(access_token === ''){
throw new Error('登陆有误');
}
const nick = localStorage.get('nick')
//非代理商 直接跳至加盟页
if(res.data.data.nick === ''){
if(nick === ''){
const aid = urlParams.get('aid')
window.location.href = "/franchise?aid="+aid
return true
@ -27,14 +60,6 @@ export async function autoLoginByToken() {
const url = new URL(window.location.href);
url.searchParams.delete('token');
window.location.replace(url.toString());
history.replaceState(null, '', url.toString());
return true
} else {
return false
}
} catch (e) {
console.error('请求异常', e)
}
}
return false
}

Loading…
Cancel
Save