a***@aluo.cn
a***@aluo.cn
  • 发布:2022-10-25 21:31
  • 更新:2024-12-10 12:16
  • 阅读:3608

UniCloud实战留言板功能遇到的“未能获取当前用户信息:当前用户为匿名身份”问题及解决方法

分类:uniCloud

跟着下面链接的教程做留言板功能
https://www.bilibili.com/video/BV17p4y1a71x/?p=20&vd_source=3db6d6011850c9ac1e496b824b883bee

问题:

匿名状态(未登录时)访问留言板时,会触发下面错误提示
“TOKEN_INVALID_ANONYMOUS_USER 未能获取当前用户信息:当前用户为匿名身份”
并且界面会跳转到登录界面,而不是正常浏览留言板

原因:
未登录状态下访问$cloudEnv_uid引起的

解决方法:在onLoad()中获取缓存中(getStorageSync部分)的登录信息,
如果获取不到则说明未正常登录,未正常登录情况下只确定审核过的留言可显示,不判断是否显示登录者发表的未审核留言
正常登录情况下则两个条件都判断
当然了解决方法应该有很多种,希望高人不吝赐教,uni-app小白先谢谢了!

视频教程里的能正常也许是因为较老版本的uni-starter可以正常吧!

guestbook.vue 源码如下
源码还解决了没有添加头像读取不到avatar_file.url出错的问题
添加了审核过的留言取消审核功能

<template>
<view>
<unicloud-db ref="udb" :where="where" v-slot:default="{data, loading, error, options}"
collection="guestbook, uni-id-users" field="_id,text,state,user_id.nickname,
user_id.avatar_file,user_id._id">
<view v-if="error">{{error.message}}</view>
<view v-else>
<view v-for="(item,index) in data" :key="index" class="item">
<view class="main">
<cloud-image v-if="item.user_id[0].avatar_file&&item.user_id[0].avatar_file.url" :src="item.user_id[0].avatar_file.url"></cloud-image>
<image v-else style="width: 50px; height: 50px; background-color: #eeeeee;" mode="aspectFit" src="@/static/uni-center/defaultAvatarUrl.png"></image>
<view>
<text class="nickname">{{item.user_id[0].nickname}}</text>
<text>{{item.text}}</text>
</view>
<button v-if="!item.state" @click="changeState(item)" type="default"><text>{{!item.state?'审核中':'审核通过'}}</text></button>
<button v-else @click="changeState(item)" type="default"><text>{{item.state?'取消审核':'审核中'}}</text></button>
</view>
</view>
</view>

    </unicloud-db>  

    <view class="submit-box">  
        <input class="input-box" v-model="text" />  
        <button type="default" @click="text?send():''" class="btn" :class="{active:text}">发送</button>  
    </view>   
</view>  

</template>

<script>
export default {
data() {
return {
text:"",
ifLogin: false,
}
},
onLoad() {
let hostUserInfo = uni.getStorageSync('uni-id-pages-userInfo')||{}
this.ifLogin = Object.keys(hostUserInfo).length != 0;
console.log('guestbook ifLogin = ',Object.keys(hostUserInfo).length != 0);
console.log('guestbook this.uniIDHasRole(AUDITOR) =',this.uniIDHasRole('AUDITOR'))
// #ifdef APP-PLUS
this.version = plus.runtime.version
// #endif
},
computed: {
where(){
if( this.uniIDHasRole('AUDITOR')){
return ''
}else{
//这里需要添加匿名用户可访问代码 暂未找到相应实现代码
/*
问题:匿名状态(未登录时)访问留言板时,会触发下面错误提示
// “TOKEN_INVALID_ANONYMOUS_USER 未能获取当前用户信息:当前用户为匿名身份”
//并且界面会跳转到登录界面,而不是正常浏览留言板
//原因:未登录状态下访问$cloudEnv_uid引起的
//解决方法:在onLoad()中获取缓存中(getStorageSync部分)的登录信息,
// 如果获取不到则说明未正常登录,未正常登录情况下只确定审核过的留言可显示,不判断是否显示登录者发表的未审核留言
//正常登录情况下则两个条件都判断
//当然了解决方法应该有很多种,希望高人不吝赐教,uni-app小白先谢谢了!

                //遇到的其他问题,数据提交数据库成功了但 this.$refs.udb.refresh() 刷新界面显示最新结果的功能未达预期,本人错在了  
                控件 <unicloud-db ref="udb" 。。。中的 ref="udb"弄丢了,补上后问题解决  
                */  
               //正常登录情况下则访问$cloudEnv_uid,否则不访问。  
                if(this.ifLogin) {  
                    console.log('guestbook where multiple')  
                    return 'state == true || user_id._id == $cloudEnv_uid'   
                } else {  
                    console.log('guestbook where alone')  
                    return 'state == true'  
                }  
            }  
        }  
    },  
    methods: {  
        async send(){  
            const db = uniCloud.database();  
            const guestbookTbl = db.collection('guestbook');  
            let res = await guestbookTbl.add({  
                "text":this.text,  
                //"user_id":"beike"  
            })  
            if(!res.result.errcode) {  
                uni.showToast({  
                    title: '发送成功',  
                    icon: 'none'  
                })  
                this.$refs.udb.refresh();  
                this.text=""  
            }else{  
                uni.showToast({  
                    title: '保存失败',  
                    text: res.result.errcode,  
                    icon: 'none'  
                })  
            }  
        },  
        async changeState0(item){  
            this.$refs.udb.update(item._id,{state:!item.state},{complete:e=>{  
                console.log(e);  
                this.$refs.udb.refresh();  
            }})  
            },  
        async changeState(item){  
            //this.$refs.udb.update(item._id,{state:!item.state},{complete:e=>{  
            //  console.log(e);  
            //  this.$refs.udb.refresh();  
            //}})  
            //视频教程中的上述方法,不可行,改为下面的 aluo 2022.10.24 原因是未添加 ref="udb"  
            const db = uniCloud.database();   
            const res = await db.collection('guestbook')    
                .doc(item._id)    
                .update({    
                    "state": !item.state,    
                }).catch((e) => {    
                    console.log(e)    
                })  
            if(!res.result.errcode){  
                uni.showToast({  
                    title:'审核成功',  
                    icon: 'none'  
                });  
                //this.text = ''  
                this.$refs.udb.refresh()//更新后刷页面不启作用! aluo 2022.10.24  
            }                     
        },  
        add(){  
            const db=uniCloud.database();  
            const guestbookTable = db.collection("guestbook");  
            guestbookTable.add({  
                "text":"这是第2条留言",  
                //"state": false,  
                //"user_id":"beike"  
            });  
        }             
    }  
}  

</script>

<style>

</style>

guestbook.schema.json
{
"bsonType": "object",
"required": [],
"permission": {
"read": "auth.uid == null || doc.state == true || doc.user_id == auth.uid || 'AUDITOR' in auth.role",
"create": "auth.uid != null",
"update": "'AUDITOR' in auth.role",
"delete": false
},
"properties": {
"_id": {
"description": "ID,系统自动生成"
},
"text": {
"bsonType": "string"
},
"state": {
"bsonType": "bool",
"forceDefaultValue": false
},
"user_id": {
"foreignKey": "uni-id-users._id",
"bsonType": "string",
"forceDefaultValue": {
"$env": "uid"
}
}
}
}

找到方法之前走了不少弯路,最初都放在了表的read权限上了,全改为true也是出现问题,一步一步去实现登录者可以看到自己未审核的留言时发现了问题所在!期间几次都想放弃了,项目几次重新开始!问题解决了心里豁然开朗,原来如此,感觉真得超好!
希望能帮助到遇到同样问题的小白朋友,高手请忽略!

1 关注 分享
2***@qq.com

要回复文章请先登录注册

w***@163.com

w***@163.com

回复 w***@163.com :
记得加反引号
2024-12-10 12:16
w***@163.com

w***@163.com

.where(`state == true || author_id == "${uniCloud.getCurrentUserInfo().uid}"`).getTemp()
2024-12-10 12:13
8***@qq.com

8***@qq.com

回复 8***@qq.com :
"permission": {
"read": "(auth.uid == null && doc.state==true) || doc.state==true ||doc.user_id==auth.uid||'AUDITOR' in auth.role",
"create": "auth.uid != null",
"update": "'AUDITOR' in auth.role",
"delete": false
},
2022-12-05 12:33
8***@qq.com

8***@qq.com

看了你的我是这样改的,还行可以了
schema里面
"permission": {
"read": "(auth.uid == null && auth.uid == null) || doc.state==true ||doc.user_id==auth.uid||'AUDITOR' in auth.role",
"create": "auth.uid != null",
"update": "'AUDITOR' in auth.role",
"delete": false
},




代码条件
where() {
if (uniCloud.getCurrentUserInfo().uid == null) {
return "state==true";
} else if (this.uniIDHasRole('AUDITOR')) {
return "";
} else {
return "state==true||user_id._id==$cloudEnv_uid";
}
}
2022-12-05 12:31