feat: improve auth guard and manual scan flow

This commit is contained in:
zm2000 2026-04-04 09:43:30 +08:00
parent 962d7157fc
commit 4ba720b4c7
14 changed files with 483 additions and 58 deletions

View File

@ -2,6 +2,8 @@
"version" : "1.0",
"configurations" : [
{
"customPlaygroundType" : "local",
"packageName" : "com.gztbyc.pda_wms",
"playground" : "standard",
"type" : "uni-app:app-android"
},

3
androidPrivacy.json Normal file
View File

@ -0,0 +1,3 @@
{
"prompt" : "none"
}

View File

@ -15,14 +15,16 @@ export default function http(
) {
let api = getApiPath(url);
console.log(api);
const token = uni.getStorageSync('token');
if (api.auth && !token) {
store.dispatch('logout');
uni.hideLoading();
return Promise.reject({
msg: `暂未登录,已阻止此次API请求: '${api.url}'`
});
}
/* 请求之前拦截器 */
Request.interceptor.request((config, cancel) => {
let token = uni.getStorageSync('token');
if (api.auth && !token) {
store.dispatch('logout');
uni.hideLoading()
throw (`暂未登录,已阻止此次API请求: '${api.url}'`);
}
token && Request.setConfig(config => {
config.header.authorization = `Bearer ${token}`
})

View File

@ -72,18 +72,27 @@ router.beforeEach(async (to, from, next) => {
const hasGetUserInfo = store.getters.user.employees_name;
console.log("有没有用户信息",hasGetUserInfo);
if (hasGetUserInfo) {
const isVisible =await store.dispatch('floatWindowManager/is_visible');
if(to.meta && to.meta.auth){
console.log(to.path);
const hasPermiss =await store.dispatch('checkPath',to.path);
if(!hasPermiss){
next({path:"/pages/403"})
return;
try {
store.dispatch('floatWindowManager/is_visible').catch(error => {
console.log('浮窗显示检查失败:', error);
});
if(to.meta && to.meta.auth){
console.log(to.path);
const hasPermiss =await store.dispatch('checkPath',to.path);
if(!hasPermiss){
next({path:"/pages/403"})
return;
}
}
}
if(to.path==from.path){
next(false);
}else{
if(to.path==from.path){
console.log('路由重复,取消跳转:', to.path);
next(false);
}else{
console.log('路由放行:', from.path, '->', to.path);
next();
}
} catch (error) {
console.log('已登录分支路由守卫异常:', error);
next();
}
@ -92,10 +101,14 @@ router.beforeEach(async (to, from, next) => {
try {
await store.dispatch('getUserInfo');
console.log("获取完成,去哪里",to)
await store.dispatch('floatWindowManager/is_visible');
store.dispatch('floatWindowManager/is_visible').catch(error => {
console.log('浮窗显示检查失败:', error);
});
if (to.path === '/pages/index/index') {
console.log('路由放行:', from.path, '->', to.path);
next();
} else {
console.log('路由重定向:', from.path, '->', to.fullPath);
next({
path: to.fullPath,
NAVTYPE: 'SwitchTab'

View File

@ -8,7 +8,7 @@ import {
removeToken
} from '@/core/utils/auth'
import { router } from '../../router'
import { goLogin } from '@/core/utils/auth-guard'
import { clearSession, goLogin } from '@/core/utils/auth-guard'
const normalizeMenus = (user = {}) => {
const sourceMenus = Array.isArray(user.menus)
@ -135,10 +135,7 @@ const actions = {
commit,
dispatch
}) {
removeToken()
commit('SET_PERMISSIONS', [])
commit('SET_USER', {})
commit('SET_ROLEID', 0)
clearSession(store)
return goLogin()
},
checkPath({

View File

@ -22,6 +22,18 @@ export function clearSession(store) {
removeToken()
if (!store) return
try {
store.commit('token', '')
} catch (e) {}
try {
store.commit('isLogin', false)
} catch (e) {}
try {
store.commit('userInfo', {})
} catch (e) {}
try {
store.commit('SET_PERMISSIONS', [])
} catch (e) {}
@ -33,11 +45,33 @@ export function clearSession(store) {
try {
store.commit('SET_ROLEID', 0)
} catch (e) {}
try {
store.commit('USER_DATA', {})
} catch (e) {}
try {
store.commit('AGENT_INFO', {})
} catch (e) {}
try {
store.commit('AUTH_TYPE', '')
} catch (e) {}
try {
store.commit('deviceInfo/CLEAR_DEVICE_INFO')
} catch (e) {}
}
function navigate(url, type) {
const currentRoute = getCurrentRoute()
if (redirecting || currentRoute === url) {
console.log('[auth-guard] 跳转已忽略:', {
url,
type,
redirecting,
currentRoute
})
return Promise.resolve()
}
@ -52,17 +86,31 @@ function navigate(url, type) {
}
if (type === 'switchTab') {
console.log('[auth-guard] 开始跳转:', { url, type })
uni.switchTab({
url,
success: () => {
console.log('[auth-guard] 跳转成功:', { url, type })
},
fail: error => {
console.log('[auth-guard] 跳转失败:', { url, type, error })
},
complete: done
})
}, true)
return
}
console.log('[auth-guard] 开始跳转:', { url, type })
uni.reLaunch({
url,
success: () => {
console.log('[auth-guard] 跳转成功:', { url, type })
},
fail: error => {
console.log('[auth-guard] 跳转失败:', { url, type, error })
},
complete: done
})
}, true)
})
}

View File

@ -94,6 +94,9 @@
"spotlight@3x" : "unpackage/res/icons/120x120.png"
}
}
},
"splashscreen" : {
"useOriginalMsgbox" : false
}
}
},

View File

@ -45,11 +45,19 @@
</view>
<!-- 广播扫描登录 -->
<view class="method-card scan-login-card">
<view class="method-card scan-login-card" @click="handleManualScan">
<view class="method-icon">
<u-icon name="scan" size="36rpx" color="#19be6b"></u-icon>
</view>
<text class="method-desc">PDA扫描工牌登录</text>
<view class="scan-login-content">
<text class="method-desc">PDA扫描工牌登录</text>
<u-button
type="success"
size="mini"
text="点击扫描工牌"
@click.stop="handleManualScan"
></u-button>
</view>
</view>
</view>
@ -532,31 +540,55 @@ export default {
parseScanCodeStrict(scanText) {
const raw = String(scanText || '').trim();
if (!raw) {
throw new Error('扫描内容为空');
return {
ok: false,
error: '扫描内容为空',
uuid: ''
};
}
if (!this.isBase64Text(raw)) {
throw new Error('扫描内容不是Base64');
return {
ok: false,
error: '扫描内容不是Base64',
uuid: ''
};
}
const decoded = this.decodeBase64Text(raw);
if (!decoded) {
throw new Error('Base64反序列化失败');
return {
ok: false,
error: 'Base64反序列化失败',
uuid: ''
};
}
let obj;
try {
obj = JSON.parse(decoded);
} catch (e) {
throw new Error('反序列化后不是JSON字符串');
return {
ok: false,
error: '反序列化后不是JSON字符串',
uuid: ''
};
}
const uuid = String(obj?.uuid || '').trim();
if (!uuid) {
throw new Error('JSON中缺少uuid键');
return {
ok: false,
error: 'JSON中缺少uuid键',
uuid: ''
};
}
return uuid;
return {
ok: true,
error: '',
uuid
};
},
parseScanUuid(scanText) {
if (!scanText) {
@ -583,6 +615,67 @@ export default {
return text;
},
normalizeUniScanResult(scanResult) {
if (!scanResult) {
return '';
}
if (typeof scanResult === 'string') {
return scanResult.trim();
}
if (typeof scanResult.result === 'string') {
return scanResult.result.trim();
}
if (Array.isArray(scanResult.result)) {
const firstResult = scanResult.result.find(item => item);
if (typeof firstResult === 'string') {
return firstResult.trim();
}
if (firstResult && typeof firstResult.data === 'string') {
return firstResult.data.trim();
}
}
if (typeof scanResult.data === 'string') {
return scanResult.data.trim();
}
return '';
},
handleManualScan() {
uni.scanCode({
onlyFromCamera: false,
scanType: ['qrCode', 'barCode', 'datamatrix', 'pdf417'],
success: (res) => {
const rawCode = this.normalizeUniScanResult(res);
if (!rawCode) {
uni.showToast({
title: '未识别到有效内容',
icon: 'none'
});
return;
}
this.handleBroadcastResult({
data: rawCode,
source: 'uni.scanCode'
});
},
fail: (error) => {
const errMsg = String(error?.errMsg || '').toLowerCase();
if (errMsg.includes('cancel')) {
return;
}
uni.showToast({
title: '扫描失败,请重试',
icon: 'none'
});
}
});
},
extractToken(payload) {
if (!payload || typeof payload !== 'object') {
return '';
@ -658,9 +751,19 @@ export default {
handleBroadcastResult(result) {
if (!this.scanning || !result || !result.data) return;
try {
const rawCode = String(result.data || '').trim(); // 扫描原文
const uuid = this.parseScanCodeStrict(rawCode); // 仅用于校验与展示
const rawCode = String(result.data || '').trim(); // 扫描原文
const parsed = this.parseScanCodeStrict(rawCode); // 仅用于校验与展示
if (!parsed.ok) {
this.scanning = true;
this.deviceCode = '';
this.scanUuid = '';
this.currentDevice = null;
this.$store.dispatch('broadcast/resume');
uni.showToast({ title: parsed.error || '扫码数据不合法', icon: 'none' });
return;
}
const uuid = parsed.uuid;
this.deviceCode = rawCode; // code = 扫描字符串
this.scanUuid = uuid;
@ -674,14 +777,6 @@ export default {
// 自动登录
this.confirmLogin();
} catch (e) {
this.scanning = true;
this.deviceCode = '';
this.scanUuid = '';
this.currentDevice = null;
this.$store.dispatch('broadcast/resume');
uni.showToast({ title: e?.message || '扫码数据不合法', icon: 'none' });
}
},
}
}
@ -923,7 +1018,6 @@ export default {
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
background: transparent;
&:active {
@ -940,6 +1034,12 @@ export default {
.method-desc {
margin: 0;
}
.scan-login-content {
display: flex;
align-items: center;
gap: 16rpx;
}
}
.device-status {

View File

@ -113,6 +113,8 @@
</template>
<script>
const BROADCAST_SETTINGS_DRAFT_KEY = 'broadcast_settings_draft';
export default {
data() {
return {
@ -150,10 +152,12 @@
this.setupScanCallback();
},
onHide() {
this.persistDraft();
// 页面隐藏时不停止广播,保持后台运行
this.removeScanCallback();
},
onUnload() {
this.persistDraft();
this.removeScanCallback();
},
methods: {
@ -167,6 +171,42 @@
const enabled = await this.$store.dispatch('setting/getValue', 'broadcast.enabled');
console.log("enabled", enabled);
this.broadcastEnabled = enabled !== 'false';
this.restoreDraft();
},
persistDraft() {
uni.setStorageSync(BROADCAST_SETTINGS_DRAFT_KEY, {
newAction: this.newAction,
newKey: this.newKey,
canChanges: this.canChanges
});
},
restoreDraft() {
const draft = uni.getStorageSync(BROADCAST_SETTINGS_DRAFT_KEY);
if (!draft) {
return;
}
let parsedDraft = draft;
if (typeof draft === 'string') {
try {
parsedDraft = JSON.parse(draft);
} catch (error) {
console.error('解析广播设置草稿失败:', error);
return;
}
}
if (parsedDraft && parsedDraft.canChanges === false) {
this.newAction = parsedDraft.newAction || this.newAction;
this.newKey = parsedDraft.newKey || this.newKey;
this.canChanges = false;
}
},
clearDraft() {
uni.removeStorageSync(BROADCAST_SETTINGS_DRAFT_KEY);
},
// 检查广播状态
@ -183,6 +223,7 @@
async saveSettings() {
if (this.canChanges) {
this.canChanges = false;
this.persistDraft();
return;
}
@ -212,6 +253,7 @@
});
if (success) {
this.clearDraft();
// 3. 设置回调函数
this.setupScanCallback();

View File

@ -44,6 +44,8 @@
</template>
<script>
import { goLogin, isLoginRoute, getCurrentRoute } from '@/core/utils/auth-guard'
export default {
data() {
return {
@ -102,14 +104,14 @@
methods: {
// 加载用户信息
loadUserInfo() {
const userData = this.$store.getters.user;
if (userData) {
const token = uni.getStorageSync('token');
const userData = this.$store.getters.user || {};
if (token && Object.keys(userData).length > 0) {
this.userInfo = userData;
} else {
this.userInfo = {};
// 如果未登录,跳转到登录页
uni.reLaunch({
url: '/pages/login/login'
});
goLogin();
}
},
@ -182,6 +184,10 @@
// 调用登出 action
await this.$store.dispatch('logout');
if (!isLoginRoute(getCurrentRoute())) {
await goLogin();
}
// 登出成功提示
uni.showToast({
title: '已退出登录',

View File

@ -33,6 +33,8 @@
</template>
<script>
import { goLogin } from '@/core/utils/auth-guard'
export default {
data() {
return {
@ -245,9 +247,7 @@
title: '请先登录',
icon: 'none'
});
uni.navigateTo({
url: '/pages/login/login'
});
goLogin();
return;
}

View File

@ -4,8 +4,13 @@
<view class="detail-display" v-if="selectedDetail">
<view class="detail-header">
<view class="search-box">
<u-search v-model="searchKeyword" placeholder="搜索运单号、货主、商品条码、车牌" bg-color="#f5f5f5" shape="round"
:show-action="false" @search="handleSearch" @clear="handleSearch"></u-search>
<view class="search-box-inner">
<u-search v-model="searchKeyword" placeholder="搜索运单号、货主、商品条码、车牌" bg-color="#f5f5f5" shape="round"
:show-action="false" @search="handleSearch" @clear="handleSearch"></u-search>
<view class="scan-camera-btn" @click="handleManualScan">
<u-icon name="camera" size="34rpx" color="#2979ff"></u-icon>
</view>
</view>
</view>
<view class="detail-actions">
@ -244,6 +249,67 @@
printBarcode(data){
this.$emit('print',data);
},
normalizeUniScanResult(scanResult) {
if (!scanResult) {
return '';
}
if (typeof scanResult === 'string') {
return scanResult.trim();
}
if (typeof scanResult.result === 'string') {
return scanResult.result.trim();
}
if (Array.isArray(scanResult.result)) {
const firstResult = scanResult.result.find(item => item);
if (typeof firstResult === 'string') {
return firstResult.trim();
}
if (firstResult && typeof firstResult.data === 'string') {
return firstResult.data.trim();
}
}
if (typeof scanResult.data === 'string') {
return scanResult.data.trim();
}
return '';
},
handleManualScan() {
uni.scanCode({
onlyFromCamera: false,
scanType: ['qrCode', 'barCode', 'datamatrix', 'pdf417'],
success: (res) => {
const rawCode = this.normalizeUniScanResult(res);
if (!rawCode) {
uni.showToast({
title: '未识别到有效内容',
icon: 'none'
});
return;
}
this.scan({
data: rawCode,
source: 'uni.scanCode'
});
},
fail: (error) => {
const errMsg = String(error?.errMsg || '').toLowerCase();
if (errMsg.includes('cancel')) {
return;
}
uni.showToast({
title: '扫码失败,请重试',
icon: 'none'
});
}
});
},
scan(data) {
if(!data.data){
return;
@ -290,6 +356,32 @@
.search-box {
flex: 1;
margin-right: 20rpx;
.search-box-inner {
display: flex;
align-items: center;
gap: 16rpx;
::v-deep .u-search {
flex: 1;
}
.scan-camera-btn {
width: 76rpx;
height: 76rpx;
border-radius: 38rpx;
background: #eef4ff;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
box-shadow: 0 4rpx 12rpx rgba(41, 121, 255, 0.12);
&:active {
opacity: 0.85;
}
}
}
}
.detail-actions {

View File

@ -68,7 +68,7 @@
</u-form-item>
<u-form-item label="创建时间">
<u-input v-model="receivingInfo.created_at" disabled />
<u-input :value="formatDate(receivingInfo.created_at)" disabled />
</u-form-item>
</view>
@ -166,6 +166,30 @@
// 调用绘制方法将二维码图案绘制到canvas上
qr.drawCanvas();
},
formatDate(dateStr) {
if (!dateStr) return '-';
try {
const normalizedDateStr = typeof dateStr === 'string' ? dateStr.replace(/-/g, '/') : dateStr;
const date = new Date(normalizedDateStr);
if (Number.isNaN(date.getTime())) {
return dateStr;
}
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hour = String(date.getHours()).padStart(2, '0');
const minute = String(date.getMinutes()).padStart(2, '0');
const second = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
} catch (error) {
console.error('日期格式化错误:', error);
return dateStr;
}
},
getStatusType(status) {
const map = {
'receiving': 'primary',

View File

@ -6,10 +6,16 @@
<view class="search-filter">
<!-- 搜索框 -->
<view class="search-box">
<u-search v-model="searchKeyword" placeholder="搜索运单号、货主、商品条码、车牌" bg-color="#f5f5f5" shape="round"
:show-action="false" @search="handleSearch" @clear="handleSearch"></u-search>
<view class="search-box-inner">
<u-search v-model="searchKeyword" placeholder="搜索运单号、货主、商品条码、车牌" bg-color="#f5f5f5" shape="round"
:show-action="false" @search="handleSearch" @clear="handleSearch"></u-search>
<view class="scan-camera-btn" @click="handleManualScan">
<u-icon name="camera" size="34rpx" color="#2979ff"></u-icon>
</view>
</view>
</view>
<!-- 筛选按钮 -->
<view class="filter-actions">
<view class="filter-buttons">
@ -323,6 +329,67 @@
this.searchKeyword = data.data;
this.handleSearch();
},
normalizeUniScanResult(scanResult) {
if (!scanResult) {
return '';
}
if (typeof scanResult === 'string') {
return scanResult.trim();
}
if (typeof scanResult.result === 'string') {
return scanResult.result.trim();
}
if (Array.isArray(scanResult.result)) {
const firstResult = scanResult.result.find(item => item);
if (typeof firstResult === 'string') {
return firstResult.trim();
}
if (firstResult && typeof firstResult.data === 'string') {
return firstResult.data.trim();
}
}
if (typeof scanResult.data === 'string') {
return scanResult.data.trim();
}
return '';
},
handleManualScan() {
uni.scanCode({
onlyFromCamera: false,
scanType: ['qrCode', 'barCode', 'datamatrix', 'pdf417'],
success: (res) => {
const rawCode = this.normalizeUniScanResult(res);
if (!rawCode) {
uni.showToast({
title: '未识别到有效内容',
icon: 'none'
});
return;
}
this.scan({
data: rawCode,
source: 'uni.scanCode'
});
},
fail: (error) => {
const errMsg = String(error?.errMsg || '').toLowerCase();
if (errMsg.includes('cancel')) {
return;
}
uni.showToast({
title: '扫码失败,请重试',
icon: 'none'
});
}
});
},
async loadStore() {
try {
@ -565,6 +632,32 @@
.search-box {
margin-bottom: 20rpx;
.search-box-inner {
display: flex;
align-items: center;
gap: 16rpx;
::v-deep .u-search {
flex: 1;
}
.scan-camera-btn {
width: 76rpx;
height: 76rpx;
border-radius: 38rpx;
background: #eef4ff;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
box-shadow: 0 4rpx 12rpx rgba(41, 121, 255, 0.12);
&:active {
opacity: 0.85;
}
}
}
}
.filter-actions {