marllen
marllen
  • 发布:2021-04-29 08:21
  • 更新:2021-05-01 03:36
  • 阅读:728

如何把 uni-id 插件用于H5页面

分类:uniCloud

一、准备

将整套uni-id插件导入编辑器,上传所有云函数及公用函数。
pages页面全部删除,自建主页,登录页,注册页,修改密码页。
保留全部VUEX部分

1.1 主页设置

  • onLoad() 即开始检测 token
  • uni_id_token 保存着 token 信息,分为两种情况:有token和没有token
  • 本地 token 正确也未过期,修改VUEX状态this.login(uni.getStorageSync('username'));
  • 本地 token 错误或者过期了,跳转登录页面 uni.reLaunch({url: '../login/login'});
  • 本地没有 token ,跳转至登录页面

import { mapState, mapMutations } from 'vuex';  
export default {  
    computed: mapState(['userName', 'hasLogin']),  
    data() {  
        return {  
        };  
    },  
    onLoad() {  
        let uid = { uid: `${uni.getStorageSync('user_id')}` };  
        let uniIdToken = uni.getStorageSync('uni_id_token');  
        if (uniIdToken) {  
        //有 token 的情况下,开始检测  
            uniCloud.callFunction({  
                name: 'user-center',  
                data: {  
                    action: 'checkToken'  
                },  
                success: e => {  
                    if (e.result.code > 0) {  
                  //检测 token 有问题,返回登录页  
                        uni.reLaunch({  
                            url: '../login/login'  
                        });  
                    }  
            this.login(uni.getStorageSync('username'));  
                },  
                fail(e) {  
                    uni.showModal({  
                        content: e.msg,  
                        showCancel: false  
                    });  
                }  
            });  
        } else {  
        //没有 token 的情况下,返回登录页  
            uni.showModal({  
                content: '请登录后再浏览',  
                showCancel: false,  
                success: res => {  
                    if (res.confirm) {  
                        uni.reLaunch({  
                            url: '../login/login'  
                        });  
                    }  
                }  
            });  
        }  
    },  
    methods: {  
        ...mapMutations(['login']),  
        login_out() {  
            uni.reLaunch({  
                url: '../login/login'  
            });  
        }  
    }  
};

1.2 登录页面设置

  • 登录后,保存了tokenusernameuser_id,然后跳转到主页
  • user_id 将用于删除云数据库uni-id-log中过多的、重复的登录记录。 文末有删除记录的云函数方法。
methods: {  
    ...mapMutations(['login']),  
    loginByPwd() {  
        const data = {  
            username: this.username,  
            password: this.password  
        };  
        uniCloud.callFunction({  
            name: 'user-center',  
            data: {  
                action: 'login',  
                params: data  
            },  
            success: (e) => {  
                if (e.result.code == 0) {  
                // 密码验证成功  
                    uni.setStorageSync('uni_id_token', e.result.token);  
                    uni.setStorageSync('username', e.result.username);  
                    uni.setStorageSync('user_id', e.result.uid);  
                    this.toMain(this.username);  
                } else {  
                // 密码验证失败  
                    uni.showModal({  
                        content: e.result.message,  
                        showCancel: false  
                    })  
                }  
            },  
            fail: (e) => {  
                uni.showModal({  
                    content: JSON.stringify(e),  
                    showCancel: false  
                })  
            }  
        })  
    },  
    toMain(userName) {  
        this.login(userName);  
        uni.reLaunch({  
            url: '../main/main',  
        });  
    }  
}

1.3 注册请求

  • 对于用户名和密码的格式要求,需自己写。
  • 注意:注册时发送给云函数user-centerdata数据的格式data:{action:'register',params: 账号,密码}
gotoRegister() {  
    uni.showLoading({  
        title: '正在提交,请稍后'  
    });  
    const data = {  
        username: this.username,  
        password: this.password  
    };  
    uniCloud.callFunction({  
        name: 'user-center',  
        data: {  
            action: 'register',  
            params: data  
        },  
        success(e) {  
            uni.hideLoading();  
            if (e.result.code === 0) {  
                uni.showToast({  
                    title: '注册成功'  
                });  
            uni.setStorageSync('uni_id_token', e.result.token);  
            uni.setStorageSync('username', e.result.username);  
            uni.reLaunch({  
                url: '../main/main'  
            });  
            } else {  
                uni.showModal({  
                    content: JSON.stringify(e.result),  
                    showCancel: false  
                });  
            }  
        },  
        fail(e) {  
            uni.hideLoading();  
            uni.showModal({  
                content: JSON.stringify(e),  
                showCancel: false  
            });  
        }  
    });  
}

1.4 补充

  • 删除多余登录记录的云函数
  • 获取当前user_id的全部登录记录数据,筛选出create_date值不是最大的全部记录,逐一删除。
  • 云函数 removeID
'use strict';  
const db = uniCloud.database();  
const dbCmd = db.command;  
exports.main = async (event, context) => {  
    const {user_id} = event;  
    let resList = await db.collection('uni-id-log')  
        .where({  
            user_id: `${user_id}`  
        })  
        .get();  
    let res = resList.data;  
    if (res.length > 1) {  
        let num = 0;  
        res.forEach((item) => {  
            if (item.create_date > num) {  
                num = item.create_date;  
            }  
        })  
        let resObjArr = await db.collection('uni-id-log')  
            .where({  
                create_date: dbCmd.neq(num)  
            })  
            .get();  
        resObjArr.data.forEach(async (item) => {  
            let resSucc = await db.collection('uni-id-log').doc(`${item._id}`).remove();  
            console.log(resSucc);  
        });  
        const date = new Date().getTime();  
        res = await db.collection('uni-id-log')  
            .where({  
                user_id: `${user_id}`  
            })  
            .get();  
        return {  
            msg: '删除成功',  
            code: 200  
        }  
    } else {  
        return {  
            msg: `当前账号仅有一次登录记录`,  
            code: 200  
        }  
    }  
};

主页onLoad()内调用

onLoad() {  
    const user_id = {user_id:`${uni.getStorageSync('user_id')}`}  
    uniCloud.callFunction({  
        name:'removeID',  
        data:user_id,  
        success: (e) => {  
            console.log(e);  
        },  
        fail: (err) => {  
            console.log(err);  
        }  
    })  
}
0 关注 分享

要回复文章请先登录注册

hws007

hws007

不判断一下本地token的过期时间?不然得老去验证云端token,应该加多个判断!在token过期前多少时间!去云端验证一下token再返回过期与否或刷新token,返回保存!这样就不用每打开一次app就去验!调用云涵数!在腾讯云可是要钱的!
2021-05-01 03:36