Home Web Front-end JS Tutorial How to implement on-demand authorized login for Vue WeChat project

How to implement on-demand authorized login for Vue WeChat project

May 23, 2018 am 11:39 AM
Authorize Log in project

This time I will bring you how to implement VueWeChat projectOn-demand authorization login, what are the precautions of implementing on-demand authorization login on Vue WeChat project, the following is a practical case, Let’s take a look.

The project uses Vue as the development framework. There are two situations when users browse the page:

  1. One requires users to log in before they can continue browsing;

  2. The other is that users can browse at will without logging in.

Pages that do not require user login may contain operations that require user information. In this case, the user needs to log in before subsequent operations can be performed. Therefore, authorization login policies need to be distinguished.

Thinking

1. Generally speaking, the H5 page we develop for WeChat requires authentication when entering the page, requiring the user to You must log in to continue browsing. However, due to product requirements, for this project we need to divide the authentication strategies of different pages and design them according to general and special:

2. In general, users are required to authorize login as soon as they enter the page. According to the routine WeChat authorized login process. After logging in, the user continues browsing.

3. In special cases, configure a whitelist for pages that do not require user login. Just enter the route that exists in the whitelist and do not enter the function that detects user login status , render the page directly.

For operations that require user information when the user is not logged in, according to my current understanding, even if it is a silent authorization based on WeChat, the page must be refreshed, and it is impossible to achieve truly senseless authorization and continue the user operation. Therefore, I chose to give the user a more friendly prompt at the front-end level to let the user understand the authorization process. The disadvantage is that the previous operation only triggered the authorized login. After the authorized login, the user needs to perform the operation again.

// routerRule.js
export default function routerRule (router, whiteList = []) {
  // other codes...
  router.beforeEach( (to, from, next ) => {
    // 因为授权登录涉及异步操作,因此使用promise,成功的回调中调用next函数
    new Promise((resolve, rejects) => {
      if ( whiteListRouter.indexOf(to.path) !== -1 ) {
        resolve()
        return
       }
      // 常规页面授权登录过程
      if (hasToken()) {
        // codes,获取用户信息并且跳转所需跳转的页面
      } else {
        // 判断用户是否已经进行微信授权
        if (hasAuthed()) {
          // 进行过微信授权之后,重定向回来的url中包含了微信的授权信息,可以将url上截取的参数发送到服务器,换取用户的token,随后进入上述有token时候的步骤
          getWechatUserInfo().then(res => {
            resolve()
          })
        } else {
          // 用户尚未进行微信授权,则调用微信授权的方法,进行授权登录。
          getWechatAuth()
        }
      }
    }).then( res => {
      next()
    })
  })
  router.afterEach(( to, from ) => {
    wxShare({ title: to.meta.title, desc: to.meta.shareDesc, link: to.meta.shareLink, logo: to.meta.shareLogo})
   })
}
Copy after login

This project is to bind the user's WeChat information with the user information of this site when the user first binds to WeChat. Therefore, after obtaining the user's WeChat authorization information, the user can be obtained token to obtain the user’s other user information on this site.

Processing operations that require permissions without logging in to the page

According to the above logic, after entering the whitelist, the entire function has been If you return it, you will not enter the following authentication process. However, if you perform operations that require permissions on such a page, you need to trigger the authorization login process, and after authorization, user information must be obtained together.

// checkLogin.js
export function checkLogin({ redirectUrl, wxAuthLoading, wxAuthLoaded, callback } = {}) {
  if (getToken()) {
    // ...
    callback && callback()
  } else {
    // 提示用户正在授权中
    wxAuthLoading && wxAuthLoading()
    getWechatAuth( redirectUrl || window.location.href ).then( res => {
      // 授权完毕,提示用户授权成功
      wxAuthLoaded && wxAuthLoaded()
    })
  }
}
Copy after login

At the same time, we need to add some operations to the routing whitelist

// routerRule.js
export default function routerRule (router, whiteList = []) {
  // other codes...
  router.beforeEach( (to, from, next ) => {
    // 因为授权登录涉及异步操作,因此使用promise,成功的回调中调用next函数
    new Promise((resolve, rejects) => {
      if ( whiteListRouter.indexOf(to.path) !== -1 ) {
        // 如果已经进行微信授权但是没有token值的,就调用以下函数获取token值
        if ( !hasToken() && hasAuthed() ) {
          getWechatUserInfo().then(res => {
            resolve()
          })
        }
        resolve()
        return
       }
      // 常规页面授权登录过程
      if (hasToken()) {
        // codes,获取用户信息并且跳转所需跳转的页面
      } else {
        // 判断用户是否已经进行微信授权
        if (hasAuthed()) {
          // 进行过微信授权之后,重定向回来的url中包含了微信的授权信息,可以将url上截取的参数发送到服务器,换取用户的token,随后进入上述有token时候的步骤
          getWechatUserInfo().then(res => {
            resolve()
          })
        } else {
          // 用户尚未进行微信授权,则调用微信授权的方法,进行授权登录。
          getWechatAuth()
        }
      }
    }).then( res => {
      next()
    })
  })
  // other codes...
}
Copy after login

Pits and imperfections

1. In this solution, after user authorization, user information must be obtained before routing jump, otherwise the WeChat authorization information on the URL will be lost and obtaining user information will fail.

2. The disadvantage of this solution is that the developer needs to add checkLogin to all operations that require permissions on the login-free page. Since this permission-requiring operation generally involves sending asynchronous requests, if you do not consider reducing unnecessary asynchronous requests, you can set an interceptor on the request method to determine the code returned by the backend. If the returned code is If the user has not logged in to the code, WeChat authorization will be performed. This approach is more convenient in the development process, but it will send some unnecessary requests to the backend when the user is not logged in, which is not good.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Vue project is packaged and sent to the server

JS implements simple shopping cart function code analysis

The above is the detailed content of How to implement on-demand authorized login for Vue WeChat project. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? Mar 21, 2024 pm 09:41 PM

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the "Login" button. (2) Select "Retrieve Password". (3) Enter the mobile phone number you used when registering your account

Discuz background login problem solution revealed Discuz background login problem solution revealed Mar 03, 2024 am 08:57 AM

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

How to log in to Kuaishou PC version - How to log in to Kuaishou PC version How to log in to Kuaishou PC version - How to log in to Kuaishou PC version Mar 04, 2024 pm 03:30 PM

Recently, some friends have asked me how to log in to the Kuaishou computer version. Here is the login method for the Kuaishou computer version. Friends who need it can come and learn more. Step 1: First, search Kuaishou official website on Baidu on your computer’s browser. Step 2: Select the first item in the search results list. Step 3: After entering the main page of Kuaishou official website, click on the video option. Step 4: Click on the user avatar in the upper right corner. Step 5: Click the QR code to log in in the pop-up login menu. Step 6: Then open Kuaishou on your phone and click on the icon in the upper left corner. Step 7: Click on the QR code logo. Step 8: After clicking the scan icon in the upper right corner of the My QR code interface, scan the QR code on your computer. Step 9: Finally log in to the computer version of Kuaishou

Can AI conquer Fermat's last theorem? Mathematician gave up 5 years of his career to turn 100 pages of proof into code Can AI conquer Fermat's last theorem? Mathematician gave up 5 years of his career to turn 100 pages of proof into code Apr 09, 2024 pm 03:20 PM

Fermat's last theorem, about to be conquered by AI? And the most meaningful part of the whole thing is that Fermat’s Last Theorem, which AI is about to solve, is precisely to prove that AI is useless. Once upon a time, mathematics belonged to the realm of pure human intelligence; now, this territory is being deciphered and trampled by advanced algorithms. Image Fermat's Last Theorem is a "notorious" puzzle that has puzzled mathematicians for centuries. It was proven in 1993, and now mathematicians have a big plan: to recreate the proof using computers. They hope that any logical errors in this version of the proof can be checked by a computer. Project address: https://github.com/riccardobrasca/flt

A closer look at PyCharm: a quick way to delete projects A closer look at PyCharm: a quick way to delete projects Feb 26, 2024 pm 04:21 PM

Title: Learn more about PyCharm: An efficient way to delete projects. In recent years, Python, as a powerful and flexible programming language, has been favored by more and more developers. In the development of Python projects, it is crucial to choose an efficient integrated development environment. As a powerful integrated development environment, PyCharm provides Python developers with many convenient functions and tools, including deleting project directories quickly and efficiently. The following will focus on how to use delete in PyCharm

PyCharm Practical Tips: Convert Project to Executable EXE File PyCharm Practical Tips: Convert Project to Executable EXE File Feb 23, 2024 am 09:33 AM

PyCharm is a powerful Python integrated development environment that provides a wealth of development tools and environment configurations, allowing developers to write and debug code more efficiently. In the process of using PyCharm for Python project development, sometimes we need to package the project into an executable EXE file to run on a computer that does not have a Python environment installed. This article will introduce how to use PyCharm to convert a project into an executable EXE file, and give specific code examples. head

How to log in to two devices on Quark How to log in to two devices on Quark Feb 23, 2024 pm 10:55 PM

How to log in to two devices with Quark? Quark Browser supports logging into two devices at the same time, but most friends don’t know how to log in to two devices with Quark Browser. Next, the editor brings users Quark to log in to two devices. Method graphic tutorials, interested users come and take a look! Quark Browser usage tutorial Quark how to log in to two devices 1. First open the Quark Browser APP and click [Quark Network Disk] on the main page; 2. Then enter the Quark Network Disk interface and select the [My Backup] service function; 3. Finally, select [Switch Device] to log in to two new devices.

See all articles