uniCloud -- uniIdRouter自动路由

2024-02-03 13:20

本文主要是介绍uniCloud -- uniIdRouter自动路由,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

自动路由

云对象响应触发needLogin

获取当前用户信息getCurrentUserInfo

实战应用

个人中心页面 

pages.json配置  uni-id自动路由

uni_modules\uni-id-pages/common 登录页面store修改


自动路由

支持的HBuilderX版本

uni-appuni-app x
3.5.0+3.99+

uniIdRouter 是一个运行在前端的、对前端页面访问权限路由进行控制的方案。

大多数应用,都会指定某些页面需要登录才能访问。以往开发者需要写不少代码。

现在,只需在项目的pages.json内配置登录页路径、需要登录才能访问的页面等信息,uni-app框架的路由跳转,会自动在需要登录且客户端登录状态过期或未登录时跳转到登录页面。

结合以下代码及注释了解如何使用uniIdRouter

{"pages": [{"path": "pages/index/index","style": {"navigationBarTitleText": "uni-app"},"needLogin": false // 当前页面是否需要登录才可以访问,此配置优先级高于uniIdRouter下的needLogin}, {"path": "pages/list/list","style": {"navigationBarTitleText": "uni-app"},"needLogin": true}, {"path": "pages/detail/detail","style": {"navigationBarTitleText": "uni-app"}}],"globalStyle": {"navigationBarTextStyle": "black","navigationBarTitleText": "uni-app","navigationBarBackgroundColor": "#F8F8F8","backgroundColor": "#F8F8F8"},"uniIdRouter": {"loginPage": "pages/index/index", // 登录页面路径"needLogin": ["pages/detail/.*" // 需要登录才可访问的页面列表,可以使用正则语法],"resToLogin": true // 自动解析云对象及clientDB的错误码,如果是客户端token不正确或token过期则自动跳转配置的登录页面,配置为false则关闭此行为,默认true}
}

以上代码,指定了登录页为首页index,然后将list页面和detail目录下的所有页面,设为需要登录才能访问。那么访问list页面和detail目录下的页面时,如果客户端未登录或登录状态过期(也就是uni_id_token失效),那么会自动跳转到index页面来登录。

与此功能对应的有两个uniCloud客户端api,uniCloud.onNeedLogin()uniCloud.offNeedLogin(),开发者在监听onNeedLogin事件后,框架就不再自动跳转到登录页面,而是由开发者在onNeedLogin事件内自行处理。详情参考:uniCloud.onNeedLogin

自动跳转到登录页面时会携带uniIdRedirectUrl参数,其值为encodeURIComponent(${跳转前的页面(包含路径和参数的完整页面地址)}),如果希望用户登录后跳转回之前的页面,可以使用此参数实现。

以下为登录页面跳转到之前访问页面的简单示例:

pages/login/login.vue

<template><view><button @click="login">login</button></view>
</template><script>export default {data() {return {uniIdRedirectUrl: ''}},onLoad(options) {this.uniIdRedirectUrl = decodeURIComponent(options.uniIdRedirectUrl)},methods: {async login() {// ...执行登录操作,在成功回调里跳转页面if (this.uniIdRedirectUrl) {uni.redirectTo({url: this.uniIdRedirectUrl})}}}}
</script>

云对象响应触发needLogin

云对象抛出uni-id token过期或token无效错误码时,会触发客户端自动跳转配置的登录页面,以下代码为一个简单示例

// todo云对象
const uniIdCommon = require('uni-id-common')
module.exports = {_before(){this.uniIdCommon = uniIdCommon.createInstance({clientInfo: this.getClientInfo()})},addTodo(title) {const {errCode,errMsg,uid} = await this.uniIdCommon.checkToken(this.getUniIdToken())if(errCode) { // uni-id-common的checkToken接口可能返回`uni-id-token-expired`、`uni-id-check-token-failed`错误码,二者均会触发客户端跳转登陆页面return {errCode,errMsg}}// ...}
}

客户端add-todo.vue

<template><!-- 略 -->
</template>
<script>export default {data() {return {}},onLoad() {},methods: {async addTodo(title){const todo = uniCloud.importObject('todo')await todo.addTodo(title) // 调用addTodo时云端checkToken如果返回了token错误、token失效的错误码就会自动跳转到配置的登录页面}}}
</script>
<style>
</style>

注意

  • pages.json内有uniIdRouter节点上述逻辑才会生效,自HBuilderX 3.5.0起创建空项目模板会自动配置空的uniIdRouter节点
  • uniIdRouter底层使用navigateTo、redirectTo、reLaunch、switchTab的拦截器进行页面跳转拦截,不会拦截进入首页,web端和app端会拦截原生tabbar点击,其他端不会拦截原生tabbar点击。 一般tabbar页面都不做自动跳转,而是在页面内再提供登录按钮。比如tabbar上有购物车或个人中心,点击购物车后在购物车页面内部会放一个提示语和按钮,告知用户需要登录。 在页面内判断用户是否登录,使用APIuniCloud.getCurrentUserInfo()

获取当前用户信息getCurrentUserInfo

HBuilderX 3.1.0+

解析客户端token获取用户信息。常用于在前端判断当前登录的用户状态和用户权限,比如根据不同的权限显示隐藏某些按钮。

注意

  • 此接口不会发送网络请求,此接口仅仅是客户端接口,不校验token的合法性以及是否过期
  • 需要搭配uni-id使用并要求客户端必须将token存储在storage内的uni_id_token
  • 如需获取role、permission需要将角色权限缓存在token内,此功能自uni-id 3.0.0 或 uni-id-common中默认开启

用法:uniCloud.getCurrentUserInfo()

该方法为同步方法。

响应参数

字段类型说明
uidNumber当前用户uid
roleArray用户角色列表。admin用户返回["admin"]
permissionArray用户权限列表。注意admin角色此数组为空
tokenExpiredNumbertoken过期时间

未能获取用户信息时返回以下结果

{uid: null,role: [],permission: [],tokenExpired: 0
}

示例
 


console.log(uniCloud.getCurrentUserInfo().role.indexOf('admin')>-1); // 如果是admin用户的话,打印结果为true

实战应用

个人中心页面 

page/self/self

<template><view class="user"><view class="top"><view class="group" @click="toUserInfo"><view class="userinfo"><view class="pic"><image v-if="hasLogin && userInfo.avatar_file && userInfo.avatar_file.url" :src="userInfo.avatar_file.url" mode="aspectFill"></image><image v-else src="../../static/images/user-default.jpg" mode="aspectFill"></image></view><view class="text" v-if="hasLogin"><view class="nickname">{{ userInfo.nickname || userInfo.username || userInfo.mobile }}</view><view class="year"><uni-dateformat :date="new Date() - 360000" :threshold="[3600, 99 * 365 * 24 * 60 * 60 * 1000]"></uni-dateformat>注册</view></view><view class="text" v-else><view class="nickname">点击登录</view></view></view><view class="more"><text class="iconfont icon-a-10-you"></text></view></view><view class="bg"><image v-if="hasLogin && userInfo.avatar_file && userInfo.avatar_file.url" :src="userInfo.avatar_file.url" mode="aspectFill"></image><image v-else src="../../static/images/user-default.jpg" mode="aspectFill"></image></view></view><view class="main"><view class="info"><view class="item"><text>33</text>获赞</view><view class="item"><text>11</text>评论</view><view class="item"><text>5</text>发文</view></view><view class="list"><view class="group"><view class="item"><view class="left"><text class="iconfont icon-a-24-bianji"></text><text class="text">我的长文</text></view><view class="right"><text class="iconfont icon-a-10-you"></text></view></view><view class="item"><view class="left"><text class="iconfont icon-a-106-xihuan"></text><text class="text">我的点赞</text></view><view class="right"><text class="iconfont icon-a-10-you"></text></view></view><view class="item"><view class="left"><text class="iconfont icon-a-21-xiugai"></text><text class="text">评论过的</text></view><view class="right"><text class="iconfont icon-a-10-you"></text></view></view></view><view class="group"><view class="item"><view class="left"><text class="iconfont icon-a-32-wenjian"></text><text class="text">关于</text></view><view class="right"><text class="iconfont icon-a-10-you"></text></view></view><view class="item"><view class="left"><text class="iconfont icon-a-5-xinxi"></text><text class="text">意见反馈</text></view><view class="right"><text class="iconfont icon-a-10-you"></text></view></view></view><view class="group"><view class="item" @click="logout"><view class="left"><text class="iconfont icon-a-73-tuichu"></text><text class="text">退出登录</text></view><view class="right"><text class="iconfont icon-a-10-you"></text></view></view></view></view></view></view>
</template><script>
import { store, mutations } from '@/uni_modules/uni-id-pages/common/store.js';
export default {data() {return {};},computed: {// 用户信息userInfo() {return store.userInfo;},// 是否登录hasLogin() {return store.hasLogin;}},methods: {//编辑个人资料toUserInfo() {uni.navigateTo({url: '/uni_modules/uni-id-pages/pages/userinfo/userinfo'});},// 是否登录goLoginPage() {if (!this.hasLogin) {uni.showToast({title: '未登录',icon: 'none'});return true;}return false;},//退出登录logout() {if (this.goLoginPage()) return;uni.showModal({title: '是否确认退出?',success: (res) => {console.log(res);if (res.confirm) {mutations.logout();}}});}}
};
</script><style lang="scss">
.user {.top {height: 300rpx;background: #bbb;padding: 0 30rpx;padding-top: var(--status-bar-height);position: relative;display: flex;align-items: center;.group {position: relative;z-index: 10;display: flex;align-items: center;justify-content: space-between;width: 100%;color: #fff;.userinfo {display: flex;width: 100%;align-items: center;.pic {width: 120rpx;height: 120rpx;border-radius: 50%;overflow: hidden;border: 2px solid #fff;image {width: 100%;height: 100%;}}.text {padding-left: 20rpx;.nickname {font-size: 44rpx;font-weight: 600;}.year {font-size: 26rpx;opacity: 0.6;padding-top: 5rpx;}}}.more {.iconfont {font-size: 40rpx;}}}.bg {position: absolute;top: 0;left: 0;width: 100%;height: 100%;overflow: hidden;image {width: 100%;height: 100%;filter: blur(20px);transform: scale(2);opacity: 0.5;}}}.main {width: 100%;min-height: 200rpx;background: #fff;border-radius: 30rpx;transform: translateY(-30rpx);padding: 30rpx 0;.info {padding: 10rpx 30rpx;display: flex;font-size: 30rpx;.item {padding-right: 20rpx;color: #888;text {font-weight: 600;color: #333;}}}.list {.group {padding: 15rpx 30rpx;border-bottom: 15rpx solid #f4f4f4;.item {display: flex;justify-content: space-between;align-items: center;padding: 25rpx 0;font-size: 36rpx;color: #555;border-bottom: 1rpx solid #f8f8f8;.left {display: flex;align-items: center;.iconfont {font-size: 38rpx;margin-right: 10rpx;}}.right {.iconfont {font-size: 26rpx;}}}.item:last-child {border: none;}}.group:last-child {border: none;}}}
}
</style>

pages.json配置  uni-id自动路由

	"uniIdRouter": {"loginPage": "uni_modules/uni-id-pages/pages/login/login-withpwd", // 登录页面路径"needLogin": ["pages/edit/edit","/uni_modules/uni-id-pages/pages/userinfo/userinfo" // 需要登录才可访问的页面列表,可以使用正则语法],"resToLogin": true // 自动解析云对象及clientDB的错误码,如果是客户端token不正确或token过期则自动跳转配置的登录页面,配置为false则关闭此行为,默认true}

uni_modules\uni-id-pages/common 登录页面store修改

退出方法  路径修改

	async logout() {// 1. 已经过期就不需要调用服务端的注销接口	2.即使调用注销接口失败,不能阻塞客户端if (uniCloud.getCurrentUserInfo().tokenExpired > Date.now()) {try {await uniIdCo.logout()} catch (e) {console.error(e);}}// 清除tokenuni.removeStorageSync('uni_id_token');// 过期时间uni.setStorageSync('uni_id_token_expired', 0)console.log(`/${pagesJson.uniIdRouter && pagesJson.uniIdRouter.loginPage ? pagesJson.uniIdRouter.loginPage: 'page/self/self'}`,pagesJson.uniIdRouter);uni.redirectTo({// pages.json是否有登录页面 有就走登录url: `/${pagesJson.uniIdRouter && pagesJson.uniIdRouter.loginPage ? pagesJson.uniIdRouter.loginPage: 'page/self/self'}`,});uni.$emit('uni-id-pages-logout')this.setUserInfo({}, { cover: true })},

hasLogin 是否登录 标识符修改  加上过期清空用户信息 返回为false

// 获取用户信息 判断是否过期 未来时间 -现在时间 
let tokenTime = uniCloud.getCurrentUserInfo().tokenExpired - Date.now()
// 100- 200 过期  清空用户信息
if (tokenTime <= 0) {hostUserInfo = {}
}
console.log(uniCloud.getCurrentUserInfo(), "getCurrentUserInfo", );const data = {userInfo: hostUserInfo,// 信息存在 && 大于 0 为未过期 (300 - 200 > 0)hasLogin: Object.keys(hostUserInfo).length != 0 && tokenTime > 0
}

这篇关于uniCloud -- uniIdRouter自动路由的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/674272

相关文章

Go路由注册方法详解

《Go路由注册方法详解》Go语言中,http.NewServeMux()和http.HandleFunc()是两种不同的路由注册方式,前者创建独立的ServeMux实例,适合模块化和分层路由,灵活性高... 目录Go路由注册方法1. 路由注册的方式2. 路由器的独立性3. 灵活性4. 启动服务器的方式5.

Go Mongox轻松实现MongoDB的时间字段自动填充

《GoMongox轻松实现MongoDB的时间字段自动填充》这篇文章主要为大家详细介绍了Go语言如何使用mongox库,在插入和更新数据时自动填充时间字段,从而提升开发效率并减少重复代码,需要的可以... 目录前言时间字段填充规则Mongox 的安装使用 Mongox 进行插入操作使用 Mongox 进行更

C语言中自动与强制转换全解析

《C语言中自动与强制转换全解析》在编写C程序时,类型转换是确保数据正确性和一致性的关键环节,无论是隐式转换还是显式转换,都各有特点和应用场景,本文将详细探讨C语言中的类型转换机制,帮助您更好地理解并在... 目录类型转换的重要性自动类型转换(隐式转换)强制类型转换(显式转换)常见错误与注意事项总结与建议类型

关于Gateway路由匹配规则解读

《关于Gateway路由匹配规则解读》本文详细介绍了SpringCloudGateway的路由匹配规则,包括基本概念、常用属性、实际应用以及注意事项,路由匹配规则决定了请求如何被转发到目标服务,是Ga... 目录Gateway路由匹配规则一、基本概念二、常用属性三、实际应用四、注意事项总结Gateway路由

IDEA如何让控制台自动换行

《IDEA如何让控制台自动换行》本文介绍了如何在IDEA中设置控制台自动换行,具体步骤为:File-Settings-Editor-General-Console,然后勾选Usesoftwrapsin... 目录IDEA如何让控制台自http://www.chinasem.cn动换行操作流http://www

vscode保存代码时自动eslint格式化图文教程

《vscode保存代码时自动eslint格式化图文教程》:本文主要介绍vscode保存代码时自动eslint格式化的相关资料,包括打开设置文件并复制特定内容,文中通过代码介绍的非常详细,需要的朋友... 目录1、点击设置2、选择远程--->点击右上角打开设置3、会弹出settings.json文件,将以下内

Python脚本实现自动删除C盘临时文件夹

《Python脚本实现自动删除C盘临时文件夹》在日常使用电脑的过程中,临时文件夹往往会积累大量的无用数据,占用宝贵的磁盘空间,下面我们就来看看Python如何通过脚本实现自动删除C盘临时文件夹吧... 目录一、准备工作二、python脚本编写三、脚本解析四、运行脚本五、案例演示六、注意事项七、总结在日常使用

SpringBoot项目启动后自动加载系统配置的多种实现方式

《SpringBoot项目启动后自动加载系统配置的多种实现方式》:本文主要介绍SpringBoot项目启动后自动加载系统配置的多种实现方式,并通过代码示例讲解的非常详细,对大家的学习或工作有一定的... 目录1. 使用 CommandLineRunner实现方式:2. 使用 ApplicationRunne

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

python实现自动登录12306自动抢票功能

《python实现自动登录12306自动抢票功能》随着互联网技术的发展,越来越多的人选择通过网络平台购票,特别是在中国,12306作为官方火车票预订平台,承担了巨大的访问量,对于热门线路或者节假日出行... 目录一、遇到的问题?二、改进三、进阶–展望总结一、遇到的问题?1.url-正确的表头:就是首先ur