feat: 完善扫码登录鉴权与跳转处理

This commit is contained in:
zm2000 2026-03-24 15:54:29 +08:00
parent 06d1989ea8
commit 006a976a76
9 changed files with 581 additions and 80 deletions

13
.hbuilderx/launch.json Normal file
View File

@ -0,0 +1,13 @@
{
"version" : "1.0",
"configurations" : [
{
"playground" : "standard",
"type" : "uni-app:app-android"
},
{
"playground" : "standard",
"type" : "uni-app:app-ios"
}
]
}

39
App.vue
View File

@ -1,18 +1,35 @@
<script>
import { getToken } from '@/core/utils/auth'
import { ensureEntry } from '@/core/utils/auth-guard'
let bootstrapping = false
let validatedToken = ''
export default {
onLaunch() {
},
onShow() {
},
methods: {
}
onLaunch() {
this.bootstrapAuth()
},
onShow() {
this.bootstrapAuth()
},
methods: {
async bootstrapAuth() {
if (bootstrapping) {
return
}
const token = getToken()
const forceValidate = !!token && token !== validatedToken
bootstrapping = true
try {
const result = await ensureEntry(this.$store, forceValidate)
validatedToken = result.loggedIn ? token : ''
} finally {
bootstrapping = false
}
}
}
}
</script>

View File

@ -1 +1,90 @@
天豹云仓的WMS_PDA项目
天豹云仓的WMS_PDA项目
## 文件说明
- `day.log`:日报记录文件,用于按天填写工作内容(今日完成、进行中、明日计划、问题与风险、备注)。
## API接口文档
- `http://192.168.11.56:6060/api/docs/system/raw`
## 接口文档与登录接口关系
### 1)接口文档(后端)
- 接口文档定义了后端可调用的 method、参数和返回结构。
- 前端并不直接写死所有 URL,而是通过本地接口映射表进行统一管理。
### 2)本地接口映射(前端“接口文档”)
- 文件:`core/request/apis.js`
- 作用:把业务别名映射为请求配置(`path/url`、`method`、`auth`)
登录相关映射:
- `user.login`
- `path: "user.login"`
- 用于账号密码登录
- `user.loginByUuid`
- `url: "https://ye4s.wms.gztbyc.com/index/wms/wms/loginByUuid"`
- 用于扫码/工牌 UUID 登录
- `user.info`
- `path: "user.info"`
- 用于拿登录后的用户信息
### 3)请求封装与实际调用关系
#### 3.1 请求入口
- 文件:`core/request/index.js`
- 统一入口:`http('user.login', data)` / `http('user.loginByUuid', data)`
#### 3.2 URL组装规则
- 文件:`core/request/request.js`
- 若配置中有 `path`:实际请求变为 `API_URL?method={path}&v=1.0&timestamp=...`
- 若配置中有完整 `url`:直接请求该 URL(如 `loginByUuid`)
#### 3.3 公共请求头
- 文件:`core/request/request.js`
- 默认头包含:
- `platform: pda`
- `project: warehouse`
> 注意:若后端提示 `project 不支持`,优先检查这里的 `project` 与业务参数中的 `project` 是否一致。
### 4)登录调用链(账号密码)
1. 页面发起:`pages/login/index.vue` -> `this.$store.dispatch('login', loginForm)`
2. 状态层处理:`core/store/modules/user.js` -> `actions.login`
3. 接口调用:`http('user.login', { username, password, device, project })`
4. 返回处理:从响应拿 `token`,调用 `setToken(token)` 写入本地
5. 页面跳转:登录页切换到 `/pages/index/index`
### 5)登录调用链(扫码/工牌)
1. 页面监听广播:`pages/login/index.vue`(`broadcast/setCallbacks` + `onResult`)
2. 获取扫码结果:`result.data`(通常是 UUID 或包含 UUID 的编码串)
3. 点击确认登录:调用 `loginByUuid(uuid)`
4. 接口调用:`http('user.loginByUuid', { uuid })`
5. 返回处理:提取 token 后 `setToken(token)`
6. 页面跳转:切换到 `/pages/index/index`
### 6)常见错误与关系定位
- 报错:`project 不支持`
- 关联:`core/request/request.js` 默认请求头 + `core/store/modules/user.js` 的 `state.app.project`
- 报错:`登录成功但未返回token`
- 关联:后端返回结构与前端 token 提取逻辑不一致
- 报错:`用户信息加载失败`
- 关联:`user.info` 接口失败、token 无效或参数不匹配
### 7)建议的排查顺序
1. 先看 `apis.js` 映射是否正确(`path/url`)
2. 再看请求头和业务参数中的 `project/device` 是否与后端一致
3. 再看接口返回结构是否包含 token
4. 最后看登录后是否成功调用 `user.info`

View File

@ -61,6 +61,12 @@ export default {
method: "POST",
isSystemApi: true
},
loginByCode: {
path: "user.loginByCode",
auth: false,
method: "POST",
isSystemApi: true
},
changeRole: {
path: "user.changeRole",
auth: true,

View File

@ -3,6 +3,7 @@ import apiList from './apis.js'
import store from '@/core/store/index.js'
import { setToken,removeToken } from '../utils/auth';
import router from '@/core/router'
import { handleTokenExpired } from '@/core/utils/auth-guard'
const Request = new coreRequest();
export default function http(
@ -39,10 +40,31 @@ export default function http(
const headers = res.header;
console.log(res);
const response = res.data;
const token = headers?.authorization || headers?.Authorization // 新的token
if (token) {
const newToken = token.substring(7) // 去掉'Bearer '前缀
setToken(newToken)
const getHeaderValue = (headerMap, key) => {
if (!headerMap) {
return '';
}
const targetKey = Object.keys(headerMap).find(item => String(item).toLowerCase() === String(key).toLowerCase());
return targetKey ? headerMap[targetKey] : '';
};
const normalizeToken = (rawToken) => {
if (!rawToken) {
return '';
}
const text = String(rawToken).trim();
if (!text) {
return '';
}
return text.startsWith('Bearer ') ? text.substring(7).trim() : text;
};
const token =
getHeaderValue(headers, 'authorization') ||
getHeaderValue(headers, 'token') ||
getHeaderValue(headers, 'x-access-token') ||
getHeaderValue(headers, 'access-token');
const normalizedToken = normalizeToken(token);
if (normalizedToken) {
setToken(normalizedToken)
}
uni.hideLoading();
if (response?.flag === "failure") {
@ -59,14 +81,10 @@ export default function http(
// token过期注销
if (res.statusCode === 401) {
removeToken();
uni.showToast({
title: '登录已过期,请重新登录',
icon: 'none',
duration: 1000,
mask: true
});
uni.reLaunch('/pages/login/index')
handleTokenExpired(store)
return Promise.reject({
msg: '登录已过期,请重新登录'
})
}
return response
})

View File

@ -8,6 +8,7 @@ import {
removeToken
} from '@/core/utils/auth'
import { router } from '../../router'
import { goLogin } from '@/core/utils/auth-guard'
const state = {
token: uni.getStorageSync("token") || "",
isLogin: uni.getStorageSync("isLogin") || false, // 是否登陆
@ -19,7 +20,7 @@ const state = {
user: {},
app: {
device: "pda",
project:"warehouse"
project:"wms"
},
permissions: [],
menus:[],
@ -115,11 +116,11 @@ const actions = {
commit,
dispatch
}) {
removeToken();
removeToken()
commit('SET_PERMISSIONS', [])
commit('SET_USER', {})
commit('SET_ROLEID', 0)
router.replace('/pages/login/index')
return goLogin()
},
checkPath({
commit,
@ -143,24 +144,80 @@ const actions = {
password
} = userInfo
return new Promise((resolve, reject) => {
const safeUsername = String(username || '').trim();
if (!safeUsername || !password) {
reject({ msg: '请输入账号和密码' })
return;
}
http('user.login', {
username: username.trim(),
username: safeUsername,
password: password,
device: state.app.device,
project:state.app.project
project: state.app.project
}).then(response => {
const {
data
} = response;
console.log("登录返回数据",data);
setToken(data.token)
resolve()
if (response && response.flag === 'failure') {
reject({ msg: response.message || '账号密码登录失败' })
return;
}
const data = response && response.data;
console.log("登录返回数据", data);
const token = data && data.token;
if (!token) {
reject({ msg: response?.message || '登录成功但未返回token' })
return;
}
setToken(token)
resolve()
}).catch(error => {
console.log("出错",error)
reject(error)
reject({ msg: error?.msg || error?.message || error?.data?.message || '登录失败' })
})
})
},
loginByCode({
commit,
state
}, payload) {
const code = String(payload?.code || payload?.uuid || '').trim();
return new Promise((resolve, reject) => {
if (!code) {
reject({ msg: '缺少工牌标识' });
return;
}
http('user.loginByCode', {
code,
device: state.app.device,
project: state.app.project
}).then(response => {
if (response && response.flag === 'failure') {
reject({ msg: response.message || '工牌登录失败' });
return;
}
const token =
response?.data?.token ||
response?.token ||
response?.data?.access_token ||
response?.access_token ||
response?.data?.accessToken ||
response?.accessToken;
if (!token) {
reject({ msg: response?.message || '登录成功但未返回token' });
return;
}
setToken(token);
resolve(response);
}).catch(error => {
reject({ msg: error?.msg || error?.message || error?.data?.message || '工牌登录失败' });
});
})
},
}
const mutations = {

111
core/utils/auth-guard.js Normal file
View File

@ -0,0 +1,111 @@
import { getToken, removeToken } from '@/core/utils/auth'
export const LOGIN_URL = '/pages/login/index'
export const HOME_URL = '/pages/index/index'
let redirecting = false
export function getCurrentRoute() {
const pages = getCurrentPages()
if (!pages || !pages.length) {
return ''
}
const current = pages[pages.length - 1]
return current?.route ? `/${current.route}` : ''
}
export function isLoginRoute(route = '') {
return route === LOGIN_URL
}
export function clearSession(store) {
removeToken()
if (!store) return
try {
store.commit('SET_PERMISSIONS', [])
} catch (e) {}
try {
store.commit('SET_USER', {})
} catch (e) {}
try {
store.commit('SET_ROLEID', 0)
} catch (e) {}
}
function navigate(url, type) {
const currentRoute = getCurrentRoute()
if (redirecting || currentRoute === url) {
return Promise.resolve()
}
redirecting = true
return new Promise(resolve => {
const done = () => {
setTimeout(() => {
redirecting = false
resolve()
}, 80)
}
if (type === 'switchTab') {
uni.switchTab({
url,
complete: done
})
return
}
uni.reLaunch({
url,
complete: done
})
})
}
export function goLogin() {
return navigate(LOGIN_URL, 'reLaunch')
}
export function goHome() {
return navigate(HOME_URL, 'switchTab')
}
export async function ensureEntry(store, forceValidate = false) {
const token = getToken()
const currentRoute = getCurrentRoute()
if (!token) {
if (!currentRoute || !isLoginRoute(currentRoute)) {
await goLogin()
}
return { loggedIn: false }
}
try {
if (forceValidate && store) {
await store.dispatch('getUserInfo', token)
}
if (!currentRoute || isLoginRoute(currentRoute)) {
await goHome()
}
return { loggedIn: true }
} catch (error) {
clearSession(store)
await goLogin()
return { loggedIn: false, expired: true, error }
}
}
export async function handleTokenExpired(store) {
clearSession(store)
const currentRoute = getCurrentRoute()
if (!isLoginRoute(currentRoute)) {
await goLogin()
}
}

9
day.log Normal file
View File

@ -0,0 +1,9 @@
2026-03-23
统计口径:当前工作区不是 git 仓库,以下内容按文件最后修改时间整理。
一、今日完成
二、问题记录
暂无
三、后续计划

View File

@ -94,54 +94,235 @@
</template>
<script>
export default {
data() {
return {
bgStyle: '',
logo: '/static/logo.png',
showQrCode: false,
showLoginConfirm: false,
scanning: false,
deviceCode: '',
currentDevice: null,
qrCodeTimer: null,
scanTimer: null,
loginData: {
deviceId: '',
deviceName: '',
loginType: '' // qrcode, broadcast, manual
},
loginForm: {
username: 'liufumingren',
password: '111111'
},
}
},
onLoad() {
const storageBg = uni.getStorageSync("bg");
const bgUrl = storageBg || "/static/loginbg.jpg";
this.bgStyle = `--bg-url: url(${bgUrl})`;
uni.hideTabBar();
},
onUnload() {
},
methods: {
async Login(){
console.log("login");
await this.$store.dispatch('login', this.loginForm)
uni.switchTab({
url:"/pages/index/index"
})
console.log("跳转页面");
import {
setToken,
getToken
} from '@/core/utils/auth'
import { goHome } from '@/core/utils/auth-guard'
export default {
data() {
return {
bgStyle: '',
logo: '/static/logo.png',
showQrCode: false,
showLoginConfirm: false,
scanning: false,
deviceCode: '',
scanUuid: '',
currentDevice: null,
qrCodeTimer: null,
scanTimer: null,
loginData: {
deviceId: '',
deviceName: '',
loginType: '' // qrcode, broadcast, manual
},
startBroadcastScan(){
console.log("模拟登录");
uni.switchTab({
url:"/pages/work/index"
})
loginForm: {
username: 'liufumingren',
password: '111111'
},
}
},
onLoad() {
const storageBg = uni.getStorageSync("bg");
const bgUrl = storageBg || "/static/loginbg.jpg";
this.bgStyle = `--bg-url: url(${bgUrl})`;
uni.hideTabBar();
this.$store.dispatch('broadcast/setCallbacks', {
onResult: this.handleBroadcastResult
});
this.$store.dispatch('broadcast/start');
},
onShow() {
this.$store.dispatch('broadcast/resume');
},
onHide() {
this.$store.dispatch('broadcast/stop');
},
onUnload() {
this.$store.dispatch('broadcast/stop');
},
methods: {
decodeBase64Text(value) {
if (!value) return '';
if (typeof atob !== 'function') return '';
const normalized = String(value).replace(/-/g, '+').replace(/_/g, '/');
const binary = atob(normalized);
try {
return decodeURIComponent(Array.prototype.map.call(binary, char => {
const code = char.charCodeAt(0).toString(16).padStart(2, '0');
return `%${code}`;
}).join(''));
} catch (e) {
return binary;
}
},
isBase64Text(value) {
if (!value) return false;
const text = String(value).trim().replace(/\s/g, '');
// 允许标准/URL安全Base64
return /^[A-Za-z0-9+/=_-]+$/.test(text) && text.length % 4 === 0;
},
parseScanCodeStrict(scanText) {
const raw = String(scanText || '').trim();
if (!raw) {
throw new Error('扫描内容为空');
}
if (!this.isBase64Text(raw)) {
throw new Error('扫描内容不是Base64');
}
const decoded = this.decodeBase64Text(raw);
if (!decoded) {
throw new Error('Base64反序列化失败');
}
let obj;
try {
obj = JSON.parse(decoded);
} catch (e) {
throw new Error('反序列化后不是JSON字符串');
}
const uuid = String(obj?.uuid || '').trim();
if (!uuid) {
throw new Error('JSON中缺少uuid键');
}
return uuid;
},
parseScanUuid(scanText) {
if (!scanText) {
return '';
}
const text = String(scanText).trim();
try {
const jsonObj = JSON.parse(text);
if (jsonObj && jsonObj.uuid) {
return String(jsonObj.uuid).trim();
}
} catch (e) {}
try {
const decoded = this.decodeBase64Text(text);
if (decoded) {
const decodedObj = JSON.parse(decoded);
if (decodedObj && decodedObj.uuid) {
return String(decodedObj.uuid).trim();
}
}
} catch (e) {}
return text;
},
extractToken(payload) {
if (!payload || typeof payload !== 'object') {
return '';
}
const keys = ['token', 'access_token', 'accessToken', 'jwt', 'jwtToken'];
for (let i = 0; i < keys.length; i++) {
const raw = payload[keys[i]];
if (raw) {
const text = String(raw).trim();
return text.startsWith('Bearer ') ? text.substring(7).trim() : text;
}
}
for (const key in payload) {
if (payload[key] && typeof payload[key] === 'object') {
const nestedToken = this.extractToken(payload[key]);
if (nestedToken) {
return nestedToken;
}
}
}
return '';
},
async loginByCode(uuid) {
const res = await this.$http('user.loginByCode', {
uuid: String(uuid).trim()
});
if (res?.flag === 'failure') {
throw new Error(res?.message || '工牌认证登录失败');
}
const token = this.extractToken(res);
if (token) {
setToken(token);
}
if (!getToken()) {
throw new Error('登录成功但未返回token');
}
},
async Login() {
try {
await this.$store.dispatch('login', this.loginForm)
await goHome()
} catch (error) {
uni.showToast({
title: error?.msg || error?.message || '登录失败',
icon: 'none'
})
}
},
async confirmLogin() {
try {
const code = String(this.deviceCode || '').trim()
if (!code) {
throw new Error('请先扫描有效工牌')
}
await this.$store.dispatch('loginByCode', { code })
await goHome()
} catch (error) {
uni.showToast({
title: error?.msg || error?.message || '工牌认证登录失败',
icon: 'none'
})
}
},
handleBroadcastResult(result) {
if (!this.scanning || !result || !result.data) return;
try {
const rawCode = String(result.data || '').trim(); // 扫描原文
const uuid = this.parseScanCodeStrict(rawCode); // 仅用于校验与展示
this.deviceCode = rawCode; // code = 扫描字符串
this.scanUuid = uuid;
this.currentDevice = {
deviceId: uuid,
deviceName: `工牌-${uuid}`
};
this.scanning = false;
uni.showToast({ title: '工牌扫描成功', icon: 'success' });
// 自动登录
this.confirmLogin();
} catch (e) {
this.deviceCode = '';
this.scanUuid = '';
this.currentDevice = null;
uni.showToast({ title: e?.message || '扫码数据不合法', icon: 'none' });
}
},
startBroadcastScan(){
this.scanning = true;
this.currentDevice = null;
this.deviceCode = '';
this.scanUuid = '';
this.$store.dispatch('broadcast/resume');
uni.showToast({
title: '请扫描工牌',
icon: 'none'
});
},
}
}
</script>
<style lang="scss" scoped>