Wechat applet - user registration and user login logic under cloud development

1, Foreword

Based on the new user registration under the cloud development of wechat applet, the concept of user login is not the same as the front-end and back-end separate development before the launch of traditional website development and cloud development:
1. The service end needs to obtain the wechat user ID from the wechat end to establish the user system in its own applet.
2. User defined login status is required.
Relatively speaking, cloud development is much more convenient. It only needs dozens of lines of code to achieve the functions of new user registration and warehousing and old user information acquisition (login). More quickly establish the user system in the applet.

2, Train of thought analysis

The implementation idea is very simple, combined with the set (table) access rights of the database and the characteristics of the user openid field when inserting data.
When the access permission of the user set (table) is set to be readable and writable only by the creator, and then judge whether the user exists in the user set, you can judge whether the user is a new user and what operations need to be performed.

3, Benefits of doing so

1. Security

The user information set (table) may store some user's privacy information, such as mobile phone number, real name information, etc. setting the access permission of the set to be readable and writable only by the creator can protect the user's privacy to the greatest extent.

2. Convenience

When the permission is readable and writable only by the creator, it is not necessary to pass in query criteria to judge whether there is this user information in the collection. In this case, you don't need to call the cloud function to obtain the user's openid first, and then pass in the openid as a query condition.

3. Robustness

When the creator is not only readable and writable, each query must be accompanied by query criteria. If the query criteria is * *_ When openid: undefined * *, you will find all user information. Assuming that the openid is not obtained or the assignment is undefined when the query occurs, it is very uncomfortable.

4, Implementation code

1. Create collections, configure permissions


2. Implementation code (app.js)

//app.js

let db = null

App({
  onLaunch() {
    if (!wx.cloud) {
      console.error('Please use 2.2.3 Or above to use cloud capabilities')
    } else {
      wx.cloud.init({
        // env Parameter Description:
        //   The env parameter determines which cloud environment resources will be requested by default for the next cloud development call (wx.cloud.xxx) initiated by the applet
        //   Please fill in the environment ID here. You can open the cloud console to view the environment ID
        //   If it is not filled in, the default environment (the first created environment) will be used
        env: 'Cloud environment id',
        traceUser: true,
      })
      db = wx.cloud.database()
      this.initData()
    }
    this.globalData = {}
  },

  /** Initialization data */
  async initData() {
    const userDataObj = await db.collection('user').get()
    let userData = null
    console.log("User data queried in the database =====>", userDataObj)
    // Determine whether there is user information
    if (userDataObj.data.length >= 1) { // Existing (old users)
      userData = userDataObj.data[0]
    } else { // Does not exist (new user)
      const serverDate = db.serverDate()
      userData = {
        avatarUrl: null,
        nickName: null,
        createTime: serverDate,
        updateTime: serverDate,
        deleteTime: null
      }
      const addRes = await db.collection('user').add({
        data: userData
      })
      console.log("New user result in database =====>", addRes)
      const newuserDataObj = await db.collection('user').get()
      console.log("New user data queried in the database =====>", newuserDataObj)
      userData = newuserDataObj.data[0]
    }
    // Put user data into cache and global variables
    wx.setStorageSync('userData', userData)
    this.globalData.userData = userData
  },

})

5, Some doubts

Some students may feel that setting the permission to be readable and writable only by the creator can not be met under some demand scenarios. For example, they need to show other users another user's mobile phone number and other information, or they want to make a small management page on the applet to review user information. It seems that it can't be realized at this time.
In fact, it can be realized. Don't forget that permission configuration is invalid for cloud functions.

Therefore, a reasonable design should realize the reading and writing requirements through cloud functions, so as to protect the security of data to the greatest extent.

6, Conclusion

Other logic in actual development will not be written. The article only introduces this design idea. Students need to consider the handling of abnormal situations and other issues by themselves.

Any questions can be left in the comments area. I reply every day. I can't talk back( (to brush points)

The above are some experience summary and understanding in my development process. If there is anything wrong, I hope the bosses will comment on it.

💥 last!!! Whether this article is useful to you or not, now that you have seen the end.
👍 Like one!!!
🤩 Of course, the incidental collection is the best.
😎 Welcome to reprint, the original is not easy, please indicate the source ✍.

😊 If you are interested in or learning applet development, you can follow me. Every article is original, every article is dry ~.

Tags: Mini Program wechat

Posted on Tue, 07 Sep 2021 16:15:08 -0400 by scheda